Created
February 17, 2023 16:33
-
-
Save pbatey/59fa993a5d2eba750d99b6236147d326 to your computer and use it in GitHub Desktop.
Function to shutdown nodejs/express http.Server gracefully
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = withShutdown | |
// This may be unnessary with server.closeIdleConnections and server.closeAllConnections added in Node v18.2.0. | |
/** | |
* Adds a shutdown function that destroys active connections | |
* (such as keep-alive). Idle connections end immediately, | |
* others are destroyed after all data is written. | |
* | |
* @param {http.Server} server http.Server instance | |
* @param {number} timeout ms to shutdown (defaulit is 1000) | |
* @returns server with shutdown() function | |
* @example | |
* const server = withShutdown(http.Server(app)) | |
* process.on('SIGINT', ()=>server.shutdown()) | |
*/ | |
function withShutdown(server, timeout=1000) { | |
server.socketIdleTimeout = timeout | |
const active = [] | |
server.on('connection', (c)=>{ | |
const i = active.length | |
active.push(c) | |
c.on('close', ()=>active.splice(i, 1)) | |
}) | |
server.shutdown = function(cb) { | |
server.close(cb) | |
active.forEach(c=>c.destroySoon()) | |
} | |
return server | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment