Skip to content

Instantly share code, notes, and snippets.

@lski
Created March 17, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lski/85ea632d42eea1a6a4a0b8a2bedada75 to your computer and use it in GitHub Desktop.
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.
/**
* 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