Skip to content

Instantly share code, notes, and snippets.

@gustavonovaes
Last active July 24, 2018 23:55
Show Gist options
  • Save gustavonovaes/8369461bf65d32a85e591737fdb6a037 to your computer and use it in GitHub Desktop.
Save gustavonovaes/8369461bf65d32a85e591737fdb6a037 to your computer and use it in GitHub Desktop.
Events to listen to on NodeJS to exit gracefully
// 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