Node.js: know when all http requests are complete

Hello, I am running my application with a Node.js cluster module and I am trying to find a way to gracefully exit the worker without losing any request.

So, I use server.close () to stop accepting new requests, but how do I know if processed requests have finished?

I came up with this hack which works great:

var http = require('http');

var server = http.createServer(function(res, req) {
  setTimeout(function() { // simulate a request which takes time (1sec) to finish                              
    req.end('hallo');
  }, 1000);
}).listen(8080);

server._requests = 0;
server.on('request', function(req, res) {
  server._requests += 1;
  res.once('finish', function() {
    server._requests -= 1;
    if (server._requests === 0)
      server.emit('no_more_requests');
  });
});

function gracefulExit() {
  server.close();
  if (server._requests === 0) process.exit(0); // exit right away
  server.once('no_more_requests', process.exit); // or wait
}

process.on('SIGTERM', gracefulExit);
process.on('SIGINT', gracefulExit);

      

But is there a more elegant way to do this?

+3


source to share


1 answer


You don't need to manually shut down the server. You can unref()

server instead . This tells node that once this server object is no longer in use and no other similar resources are being used, the process can exit.

See nodejs server.unref()

doc for details
.



Please note, you cannot do this immediately, because then your server will start and the process will end before any requests are processed. Instead, you will need to decide sometime in the future after your server is up and running and then you want server.unref()

it and let it shut down.

Please note, the same functionality exists for timers in node.js, so you can decide if the timer should support your processing or not.

0


source







All Articles