如何使用Hapi将数据流式传输到浏览器? [英] How do I stream data to browsers with Hapi?

查看:92
本文介绍了如何使用Hapi将数据流式传输到浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用流使用Hapi将数据发送到浏览器,但无法确定我们该如何做.具体来说,我正在使用请求模块.根据文档,reply对象接受流,所以我尝试了:

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'));

引发错误.在文档中说流对象必须与 streams2 兼容,所以我尝试了:

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')));

现在,它不会引发服务器端错误,但是在浏览器中,请求永远不会加载(使用chrome).

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

然后我尝试了这个:

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

并且在控制台中输出了 数据,所以我知道流不是问题,而是Hapi.如何在Hapi中运行流媒体?

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?

推荐答案

尝试使用 Readable.wrap :

var Readable = require('stream').Readable;
...
function (request, reply) {

  var s = Request('http://www.google.com');
  reply(new Readable().wrap(s));
}

使用Node 0.10.x和hapi 8.x.x测试.在我的代码示例中,Request是节点请求模块,而request是传入的hapi请求对象.

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.

更新

另一种可能的解决方案是侦听Request中的响应"事件然后replyhttp.IncomingMessage是正确的读取流.

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);
     });
}

这需要较少的步骤,并且还允许开发人员在传输之前将用户定义的属性附加到流.这对于设置200以外的状态代码很有用.

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.

这篇关于如何使用Hapi将数据流式传输到浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆