Skip to content

Instantly share code, notes, and snippets.

@RoyalRajdeep
Created October 16, 2019 05:12
Show Gist options
  • Save RoyalRajdeep/fd660b2bc3aa1f5118ec73011e8efb4e to your computer and use it in GitHub Desktop.
Save RoyalRajdeep/fd660b2bc3aa1f5118ec73011e8efb4e to your computer and use it in GitHub Desktop.
// Register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()
process.stdin.resume();//so the program will not close instantly
function exitHandler(options, exitCode) {
if (options.cleanup) console.log('clean');
if (exitCode || exitCode === 0) console.log(exitCode);
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}));
/* This solution has numerous issues.
(1) It doesn't report signals to parent processes.
(2) It doesn't convey the exit code to the parent process.
(3) It doesn't allow for Emacs-like children that ignore Ctrl-C SIGINT.
(4) It doesn't allow asynchronous cleanup.
(5) It doesn't coordinate a single stderr message across multiple cleanup handlers. I've written a module that does all this, github.com/jtlapp/node-cleanup, originally based on the cleanup.js solution below, but greatly revised based on feedback. I hope it proves helpful. –
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment