How to transfer data to browsers using Hapi?

I am trying to use streams to send data to a browser using Hapi, but I cannot figure out how to do this. In particular, I use the request module. According to the docs, the reply object accepts the stream, so I tried:

 reply(request.get('https://google.com')); 

Throws an error. The docs say that the stream object must be compatible with streams2 , so I tried:

 reply(streams2(request.get('https://google.com'))); 

Now this does not cause a server-side error, but the request never loads in the browser (using chrome).

Then I tried this:

 var stream = request.get('https://google.com'); stream.on('data', data => console.log(data)); reply(streams2(stream)); 

And the data was output to the console, so I know that the thread is not a problem, but rather Hapi. How can I get streams in Hapi for work?

+7
request streaming hapijs
source share
1 answer

Try using Readable.wrap :

 var Readable = require('stream').Readable; ... function (request, reply) { var s = Request('http://www.google.com'); reply(new Readable().wrap(s)); } 

Tested with Node 0.10.x and hapi 8.xx In my Request code example, there is a node -request module, and Request is the incoming hapi request object.

UPDATE

Another possible solution would be to listen for the response event from Request , and then reply using http.IncomingMessage , which is the correct read stream.

 function (request, reply) { Request('http://www.google.com') .on('response', function (response) { reply(response); }); } 

This requires fewer steps, and also allows the developer to attach user-defined properties to the stream before passing. This can be useful when setting status codes other than 200.

+12
source share

All Articles