Last active
July 24, 2018 23:55
-
-
Save gustavonovaes/8369461bf65d32a85e591737fdb6a037 to your computer and use it in GitHub Desktop.
Events to listen to on NodeJS to exit 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
// prevent the program to close instantly | |
process.stdin.resume(); | |
function exitHandler(options, err) { | |
if (options.cleanup) console.log('clean'); | |
if (err) console.log(err.stack); | |
if (options.exit) process.exit(); | |
} | |
// do something when app is closing | |
process.on('exit', exitHandler.bind(null,{cleanup:true})); | |
// catches ctrl+c event | |
process.on('SIGINT', exitHandler.bind(null, {exit:true})); | |
// catches "kill pid" (for example: nodemon restart) | |
process.on('SIGUSR1', exitHandler.bind(null, {exit:true})); | |
process.on('SIGUSR2', exitHandler.bind(null, {exit:true})); | |
// catches uncaught exceptions | |
process.on('uncaughtException', exitHandler.bind(null, {exit:true})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment