How can I output data before I end the response?

Adam Halasz picture Adam Halasz · Jun 6, 2011 · Viewed 16.4k times · Source

Here is my snippet I tested it in Chrome 11, and Firefox 4:

var http = require('http');

http.createServer(function(request, response){
   // Write Headers
   response.writeHead(200);

   // Write Hello World!
   response.write("Hello World!");

   // End Response after 5 seconds
   setTimeout(function(){ 
        response.end(); 
   }, 5000);

}).listen(8000);

As you can see I timed out the response.end() so I can test if response.write is outputted before the response.end. In my experience though it is not.

Is there a way to output the data before ending the response, something like sending the data in packets?

Answer

Geoff Chappell picture Geoff Chappell · Jun 7, 2011

If you change the content type to text/plain -- e.g:

// Write Headers
response.writeHead(200, {'Content-Type': 'text/plain'});

then firefox will show the content immediately. Chrome still seems to buffer (if you write a bunch more content, chrome will show it immediately).