Skip to content

Instantly share code, notes, and snippets.

@bennycode
Created October 8, 2019 10:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennycode/b2b378385b05bb7db4bc7ec3600f7f40 to your computer and use it in GitHub Desktop.
Save bennycode/b2b378385b05bb7db4bc7ec3600f7f40 to your computer and use it in GitHub Desktop.
Node.js process.exit cleanup
function emitExit(signal: string) {
const exitCode = 0;
console.log(`Received "${signal}" signal. Will terminate with exit code "${exitCode}".`);
process.exit(exitCode);
}
// Catches Ctrl + C events
process.on('SIGINT', () => emitExit('SIGINT'));
// Catches "kill pid" events (for example: nodemon restarts)
process.on('SIGUSR1', () => emitExit('SIGUSR1'));
process.on('SIGUSR2', () => emitExit('SIGUSR2'));
// Catches unhandled errors
process.on('uncaughtException', error => {
console.log('Unhandled error.', error);
process.exit(1);
});
// Catches unhandled Promise rejections
process.on('unhandledRejection', error => {
console.log('Unhandled Promise rejection.', error);
process.exit(1);
});
// `process.exit` callback
process.on('exit', (code: number) => {
console.log(`App exits with code "${code}". Synchronous cleanup can be done here.`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment