Graceful shutdown of a node.JS HTTP server

Bryan Field picture Bryan Field · Mar 10, 2011 · Viewed 24.1k times · Source

Here is a simple webserver I am working on

var server = require("http").createServer(function(req,resp) {
    resp.writeHead(200,{"Content-Type":"text/plain"})
    resp.write("hi")
    resp.end()
    server.close()
})
server.listen(80, 'localhost')
// The shortest webserver you ever did see! Thanks to Node.JS :)

Works great except for keep-alive. When the first request comes in, server.close gets called. But the process does not end. Actually the TCP connection is still open which allows another request to come through which is what I am trying to avoid.

How can I close existing keep-alive connections?

Answer

Ben Last picture Ben Last · Dec 16, 2011

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