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

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

问题描述

我正在尝试使用流将数据发送到带有 Hapi 的浏览器,但无法弄清楚我们的方法.具体来说,我正在使用 request 模块.根据文档,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 的 'response' 事件 然后 reply 使用 http.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天全站免登陆