Streaming Http responses with NodeJS

有些话、适合烂在心里 提交于 2019-12-17 14:04:18

问题


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

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?


回答1:


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.

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

Related Question

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

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.

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



来源:https://stackoverflow.com/questions/9751711/streaming-http-responses-with-nodejs

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