How to close ExpressJs server correctly?

I have an ExpressJs server (version 4.X) and I need to stop the server correctly.

Since some requests can last a long time (1-2 seconds), I have to reject new connections and wait for all current requests to finish. Killing a server in the middle of some tasks can cause the server to be in an unstable state.

I tried the following code:

//Start
var app = express();
var server = https.createServer(options, app);
server.listen(3000);


//Stop
process.on('SIGINT', function() {
    server.close();
});

However, this code does not close keep-alive connections, and some clients may communicate for a long time.

So how can I properly close all connections?

+4
source share
1 answer

, .

var app = express(),
    shuttingDown = false;

app.use(function(req, res, next) {
    if(shuttingDown) {
        return;
    }
    next();
});

var server = https.createServer(options, app);
server.listen(3000);

process.on('SIGINT', function() {
    shuttingDown = true;
    server.close(function(){
        process.exit();
    });
});
+4

All Articles