How do I stream data to browsers with Hapi?

馋奶兔 提交于 2019-12-30 08:17:14

问题


I'm trying to use streams to send data to the browser with Hapi, but can't figure our how. Specifically I am using the request module. According to the docs the reply object accepts a stream so I have tried:

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

The throws an error. In the docs it says the stream object must be compatible with streams2, so then I tried:

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

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

I then tried this:

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

And in the console data was outputted, so I know the stream is not the issue, but rather Hapi. How can I get streaming in Hapi to work?


回答1:


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 using Node 0.10.x and hapi 8.x.x. In my code example Request is the 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 with the http.IncomingMessage which is a proper 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 transmission. This can be useful in setting status codes other than 200.




回答2:


for Happi 17.9.0

I found it !! the problem is with the gzip compression

to disable it just for event-stream you need provide the next config to Happi server

const server = Hapi.server({
  port: 3000, 
  ...
  mime:{
    override:{
      'text/event-stream':{
        compressible: false
      }
    }
  }
});

in the handler I use axios because it support the new stream 2 protocol

async function handler(req, h) {
    const response = await axios({
        url: `http://some/url`,
        headers: req.headers,
        responseType: 'stream'
    });

    return response.data.on('data',function (chunk) {
        console.log(chunk.toString());
    })

    /* Another option with h2o2, not fully checked */
    // return h.proxy({
    //     passThrough:true,
    //     localStatePassThrough:true,
    //     uri:`http://some/url`
    // });
};


来源:https://stackoverflow.com/questions/31210950/how-do-i-stream-data-to-browsers-with-hapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!