Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

node.js - Streaming Http responses with NodeJS

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>
');
    res.write('<body>
');
    res.write('hello ');
    res.write('</body>
');
    res.write('</html>
');
    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...