Created
September 27, 2015 14:40
-
-
Save soletan/701fefc7727c2bc7c170 to your computer and use it in GitHub Desktop.
How to shut down express js gracefully while supporting keep-alive
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
// 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(); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a final note, gracefully shutting down expressjs application (involving database connection) was working finally using the latest approach given above.