How can I output data before I end the response?

There actually is a way that you can do this without setting Content-Type: text/plain and still use text/html as the Content-Type, but you need to tell the browser to expect chunks of data.

This can be done easily like this:

var http = require('http');

http.createServer(function(request, response) {

    response.setHeader('Connection', 'Transfer-Encoding');
    response.setHeader('Content-Type', 'text/html; charset=utf-8');
    response.setHeader('Transfer-Encoding', 'chunked');

    response.write('hello');

    setTimeout(function() {
        response.write(' world!');
        response.end();
    }, 10000);

}).listen(8888);

You should be aware though, that until response.end() is called the request is still taking place and blocking other requests to your nodejs server.
You can easily test this by opening calling this page (localhost:8888) on two different tabs. One of them will wait 10 seconds, and the other will only get the beginning of the response once the first response ends (meaning you’ll wait 10 seconds for the beginning of the response and another 10 seconds till the end of the response, using this code).

You can probably pass this obstacle too by running a couple of nodejs processes and load balancing between them, but then this begins to get much more complicated, and is a thread that should be taken else where… 🙂

Leave a Comment