This runs without error:
const app = express();
const server = app.listen(3900, '0.0.0.0', () => {
console.log('listening...');
});
process.once('SIGINT', () => {
console.log('got SIGINT.')
setTimeout(() => {
console.log('ending process due to SIGINT + subsequent Timeout.')
process.exit(0);
}, 3000);
server.closeIdleConnections(); // <<<
server.closeAllConnections(); // <<<<
server.close(err => {
if (err) {
console.error(err);
}
console.log('closed server, and now shutting down due to SIGINT.')
process.exit(0);
});
});
but my question is - is this the best way to stop accepting new connections before ending the existing connections/requests?
how are "idle" connections defined?
I guess "best" is subjective and it depends on the application. However, calling the synchronous
server.closeAllConnections()before allowing the asynchronousserver.close()to finish it's work is not the most graceful way to stop any ongoing connections (those currently sending a request or waiting for a response). In short, I would say no this is not the most graceful way to stop accepting new connections before ending existing connections due to the abrupt nature ofcloseAllConnections.I'll link you to the documentation which states that idle connections are connections connected to this server which are not sending a request or waiting for a response.
To make your
SIGINThandler more graceful, I would recommend a slight modification by removing the call toserver.closeAllConnections()and nesting yoursetTimeoutinside of theclosecallback. Something along these lines:Note, that the callback to
server.closewill only receive an error if you are attempting to shutdown a server that was not running. This is noted in the documentation fornet.Server.close().