Created
October 8, 2019 10:12
-
-
Save bennycode/b2b378385b05bb7db4bc7ec3600f7f40 to your computer and use it in GitHub Desktop.
Node.js process.exit cleanup
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
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