Skip to content

Instantly share code, notes, and snippets.

@thedillonb
Last active April 23, 2017 00:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedillonb/604edf54aa8811929a3f to your computer and use it in GitHub Desktop.
Save thedillonb/604edf54aa8811929a3f to your computer and use it in GitHub Desktop.
NodeJS Graceful shutdown of a HTTP server
'use strict';
const http = require('http');
function addGracefulShutdown(server) {
const oldClose = server.close;
const connections = {};
let shouldDestroy = false;
let connectionId = 0;
function destroy(socket) {
if (socket._isIdle && shouldDestroy) {
socket.destroy();
delete connections[socket._connectionId];
}
}
server.on('request', function(req, res) {
req.socket._isIdle = false;
res.on('finish', function() {
req.socket._isIdle = true;
destroy(req.socket);
});
});
server.on('connection', function(socket) {
let id = connectionId++;
socket._isIdle = true;
socket._connectionId = id;
connections[id] = socket;
socket.on('close', function() {
delete connections[id];
});
});
server.close = function(cb) {
shouldDestroy = true;
oldClose.apply(server, function() {
let args = arguments;
process.nextTick(function() {
cb(arguments);
});
});
Object.keys(connections).forEach(key => {
destroy(connections[key]);
});
};
return server;
}
function extendPrototype() {
http.Server.prototype.extendClose = function() {
return addGracefulShutdown(this);
}
};
extendPrototype();
const server = http.createServer(function(req, res) {
setTimeout(function() {
res.writeHead(200);
res.end('AWesome');
}, 1000 * 5);
}).extendClose();
server.listen(4242, () => console.log('Listening!'));
process.on('SIGINT', function() {
console.log('SIGINT received');
server.close(function(err) {
console.log('Whats good in the hood!?!?');
process.exit();
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment