开发者

Stream with Node.js doesn't work

开发者 https://www.devze.com 2023-01-17 08:27 出处:网络
I know that with Node.js you can stream data. But why doesn\'t this code work: var sys开发者_开发百科 = require(\'sys\'),

I know that with Node.js you can stream data.

But why doesn't this code work:

var sys开发者_开发百科 = require('sys'),
http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("hello");
    res.write("world");
}).listen(80);

Seems that I have to have res.end() after the last res.write() to be able to send the data to the browser.


I think the chunk has to be a certain size before it's sent.


Actually, it seems more like the output has to be a certain size before the browser renders it. Probably the buffer at the browser end. When you send res.end() the browser flushes this buffer and renders all that's in the buffer straightaway. However, if no res.end() is send, the browser awaits till its buffer is filled.

I tried experimenting the following block of code with Firefox and curl.

var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("hello\n");
    for (var i = 0; i < 100; i++) {
      setTimeout(function() {
        res.write("world lotsa text here lotsa text\n");
      }, 400*i);
  }
}).listen(3000);

You can try it yourself by heading to http://localhost:3000/ after running node with the above code.

I then tried the same thing with curl, and every line appeared straightaway as it was sent from the server.

The curl command I used was simply:

curl http://localhost:3000/

Note the newlines I inserted in the res.write as curl will wait for the newlines before outputting to stdout.

0

精彩评论

暂无评论...
验证码 换一张
取 消