Last active
April 23, 2017 00:59
-
-
Save thedillonb/604edf54aa8811929a3f to your computer and use it in GitHub Desktop.
NodeJS Graceful shutdown of a HTTP server
This file contains hidden or 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
'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