NodeJS Streaming HTTP Chunked Responses

Home / NodeJS Streaming HTTP Chunked Responses

NodeJS Streaming HTTP Chunked Responses

December 9, 2015 | Article | No Comments

NodeJS is extremely streamable, including HTTP responses. HTTP being a first-class protocol in Node, make HTTP response streamable in very convenient way.

HTTP chunked encoding allows a server to keep sending data to the client without ever sending the body size. Unless we specify a “Content-Length” header, Node HTTP server sends the header

Transfer-Encoding: chunked

to client, which makes it wait for a final chunk with length of 0 before giving the response as terminated.

This can be useful for streaming data – text, audio, video – or any other into the HTTP client.

Streaming Example

Here we are going to code an pipes the output of a child process into the client:

var spawn = require('child_process').spawn;

require('http').createServer(function(req, res) {
    var child = spawn('tail', ['-f', '/var/log/system.log']);
    res.on('end', function() {

Here we are creating an HTTP server and binding it to port 4000.

When there is a new request, we launch a new child process by executing the command “tail -f /var/log/system.log” which output is being piped into the response.

When response ends (because the browser window was closed, or the network connection severed, etc), we kill the child process so it does not hang around indefinitely.

, ,

About Author

about author


A man who is obsessed to low level technology.

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Share Buttons and Icons powered by Ultimatelysocial