Skip to content

Instantly share code, notes, and snippets.

@soletan
Created September 27, 2015 14:40
Show Gist options
  • Save soletan/701fefc7727c2bc7c170 to your computer and use it in GitHub Desktop.
Save soletan/701fefc7727c2bc7c170 to your computer and use it in GitHub Desktop.
How to shut down express js gracefully while supporting keep-alive
// this is an excerpt of essential but non-working part extracted from local expressjs application ...
var app = require( "express" )();
var httpServer = require( "http" ).createServer( app );
httpServer.on( "connection", function( socket ) {
socket.unref();
} );
httpServer.listen( CONFIG.port, CONFIG.ip );
app.use( function _gracefulShutdownSupporter( req, res, next ) {
// mark connection to be actively serving request now
req.connection.ref();
// wrap genuine end() on response to clear mark afterwards
res._genuineEnd = res.end;
res.end = function() {
var args = [], i, l, a, injected = false,
socket = req.connection;
for ( i = 0, l = arguments.length, args = []; i < l; i++ ) {
a = arguments[i];
if ( typeof a === "function" && !injected ) {
injected = true;
args[i] = (function( genuine ) {
return function() {
socket.unref();
return genuine.apply( this, arguments );
};
})( a );
} else {
args[i] = a;
}
}
if ( !injected ) {
args.push( function() {
socket.unref();
} );
}
return res._genuineEnd.apply( this, args );
};
next();
} );
@soletan
Copy link
Author

soletan commented Sep 28, 2015

As a final note, gracefully shutting down expressjs application (involving database connection) was working finally using the latest approach given above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment