Created
March 17, 2020 13:28
-
-
Save lski/85ea632d42eea1a6a4a0b8a2bedada75 to your computer and use it in GitHub Desktop.
A handler for Node process ending. Good for clean up. By default on Ctrl+C, process.exit() and uncaught exceptions.
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
/** | |
* Handles cleanup after basic close events, if the handler returns nothing | |
* | |
* @param {Function} handler | |
* @param {Array<string>} [events=['SIGINT', 'uncaughtException', 'exit']] | |
*/ | |
export const onProcessExit = ( | |
handler, | |
events = ['SIGINT', 'uncaughtException', 'exit'] | |
) => { | |
const closeHandler = type => exitCode => { | |
// NB: Should probably log if it equals uncaughtException... | |
// Ensure the handler response is a promise, then handle the value returned | |
Promise.resolve(handler(type, exitCode)).then(returned => { | |
if (shouldExit(returned)) { | |
process.exit(exitCode); | |
} | |
}); | |
}; | |
for (const event of events) { | |
process.on(event, closeHandler(event)); | |
} | |
}; | |
const shouldExit = (handlerResponse, exitType) => { | |
// If the handler explicitly returns a bool to say whether to close, then make it exit (unless the eventType is 'exit') | |
return typeof handlerResponse === 'boolean' | |
? handlerResponse | |
: exitType !== 'exit'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment