使用NodeJS流式传输Http响应 [英] Streaming Http responses with NodeJS

查看:589
本文介绍了使用NodeJS流式传输Http响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验一个简单的NodeJS HTTP服务器的各种响应。
我想要实现的效果是更快的网页视觉呈现。由于响应是通过 transfer-encoding:chunked 流式传输到浏览器(对吗?)我以为我可以先渲染页面布局,然后在延迟后渲染其余数据。

I am experimenting with various responses from a simple NodeJS HTTP server. The effect I am trying to achieve is faster visual rendering of a web page. Since the response is streamed to the browser with transfer-encoding: chunked (right?) I was thinking I could render the page layout first and the rest of the data after a delay.

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
        , 'Transfer-Encoding': 'chunked'
    });
    res.write('<html>\n');
    res.write('<body>\n');
    res.write('hello ');
    res.write('</body>\n');
    res.write('</html>\n');
    setTimeout(function () {
        res.end('world');
    },1500);
}).listen(3000, '127.0.0.1');

问题似乎是在之前没有发送回复res.end('world')除非已经写入的数据足够长,所以例如 res.write(new Array(2000).join('1')) 而不是那个 res.write('hello'),就可以了。

The thing is that it seems as if the response isn't sent until res.end('world') unless the already written data is long enough, so for instanceres.write(new Array(2000).join('1')) instead of thatres.write('hello'), would do the trick.

节点是否缓冲我的写入,直到数据足够大才能发送?如果是这种情况,块大小是否可配置?

Is Node buffering my writes until the data is sizable enough to be sent? If that is the case, is the chunk size configurable?

推荐答案

在读取结束标记之前,浏览器可能无法呈现数据。尝试输出纯文本而不是html标签来测试它。

It's possible that the browser is not rendering the data until the closing tags have been read. Try outputting plain text instead of html tags to test this.

您是否看到任何输入进入firebug / chrome检查器?

Do you see any input coming into firebug / chrome inspector?

相关问题

http://nodejs.org/api/stream.html#stream_stream_write_string_encoding_fd


将具有给定编码的字符串写入流。如果
字符串已刷新到内核缓冲区,则返回true。返回false为
表示内核缓冲区已满,并且数据将在未来发送出

Writes string with the given encoding to the stream. Returns true if the string has been flushed to the kernel buffer. Returns false to indicate that the kernel buffer is full, and the data will be sent out in the future.

因此输出 .write()方法的结果。看看它是返回true还是false。

So output the results of .write() methods. See if it returns a true or false.

这篇关于使用NodeJS流式传输Http响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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