I am trying to find a way to know if there are requests pending on the server so I can wait for them to finish in order to gracefully shutdown the server. What I have tried so far is:
var express = require("express");
var app = express();
var count = 0;
app.use(function(req, res, next){
count++;
console.log(count);
next();
res.on("end", function(){ //PROBLEM HERE! This event does not exists!!!
count = count - 1;
console.log(count);
});
});
app.get("/", function(req, res, next){
res.send("Ok!");
});
process.on('SIGINT', function () {
if(count === 0) process.exit();
else console.log("Can't shutdown! Pending requests...");
});
var server = app.listen(8021);
So what is the best way to handle this case??? I am stucked.
EDIT: It was supposed to be quite an easy task. Acording to http://nodejs.org/api/net.html#net_server_close_callback
Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. Optionally, you can pass a callback to listen for the 'close' event.
I can simply do:
process.on('SIGINT', function () {
console.log("Exiting");
server.close();
server.on("close", function(){
console.log("Exited");
process.exit(0);
});
});
But my callback for on close is never called. Also tried:
process.on('SIGINT', function () {
console.log("Exiting");
server.close(function(){
console.log("Exited");
process.exit(0);
});
});
But it doesn't work either.
You can try using server.getConnections to get the number of concurrent connections. If that returns 0, then you're safe to exit.