Question

I'm playing around with node.js sample demo with HTTP Streams (Content-Type: chunked).

var http = require('http');

var server = http.Server(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  setInterval(function() {
     res.write('world\n');
  },2000);

  res.write('hello ');
});

server.listen(3000);

Now when I use chrome to view the page, it just times out and I never get to see anything on the screen. Whereas using cURL seems to show me the contents as it is received.

$ curl localhost:3000
hello world
world
world
world

Is this the browser default behavior where it won't show anything unless it has complete data? Seems like a waste to throw away the data and show a timeout error.

Was it helpful?

Solution

You need to call res.end in order to see the output in the browser.

Try, for example, adding this after res.write('hello'):

setTimeout(function(){res.end();}, 5000);

After five seconds you'll see something like:

Hello world
world

My guess is that cURL shows output right away because it doesn't care about the content type, whereas the browser, which does care, may want more of the response before it shows anything.

You can also try streaming the response by changing the transfer encoding; check out this question for more info on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top