Graceful shutdown of a node.JS HTTP server

You can control the idle timeout for a connection, so you can set how long a keep-alive connection will remain open. For example:

server=require('http').createServer(function(req,res) {
    //Respond
    if(req.url.match(/^\/end.*/)) {
        server.close();
        res.writeHead(200,{'Content-Type':'text/plain'});
        res.end('Closedown');
    } else {
        res.writeHead(200,{'Content-Type':'text/plain'});
        res.end('Hello World!');
    }
}).listen(1088);
//Set the idle timeout on any new connection
server.addListener("connection",function(stream) {
    stream.setTimeout(4000);
});

We can test this with netcat:

ben@quad-14:~/node$ echo -e "GET /test HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

c
Hello World!
0

after 4 seconds, the connection closes

And now we can show that closing the server works: after all idle connections are dropped, the server exits:

ben@quad-14:~/node$ echo -e "GET /end HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

9
Closedown
0

after 4 seconds, the connection closes and the server exits

Leave a Comment

tech