Http streaming responses with NodeJS

I am experimenting with various answers from a simple NodeJS HTTP server. The effect I'm trying to achieve is speeding up the visual display of a web page. Since the response is sent to the browser using transfer-encoding: chunked (right?), I thought I could display the page layout first, and the rest after the 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 fact is that it seems that the answer is not sent until res.end('world') if the data already recorded is long enough, therefore, for example, res.write(new Array(2000).join('1')) instead res.write('hello') will do the trick.

Is Node buffering my records until the data is big enough to send? If so, is the block size adjustable?

+6
source share
1 answer

The browser may not transmit data until the closing tags have been read. Try displaying plain text instead of html tags to verify this.

Do you see any input in the Firebug / chrome inspector?

Question related to us

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

Writes a string with this encoding to the stream. Returns true if the string was flushed to the kernel buffer. Returns false to indicate that the kernel buffer is full and data will be sent in the future.

So, output the results of .write() methods. See if it will return true or false.

+3
source

Source: https://habr.com/ru/post/910995/


All Articles