What is exit-hook?
The exit-hook npm package allows developers to easily register callbacks to be executed when a Node.js process exits. This can be particularly useful for cleaning up resources, saving state, or performing other shutdown tasks in a Node.js application.
What are exit-hook's main functionalities?
Registering a simple exit hook
This feature allows you to register a callback function that will be called when the process exits. The code sample demonstrates how to register a simple exit hook that logs a message to the console when the process exits.
const exitHook = require('exit-hook');
exitHook(() => {
console.log('Process is exiting');
});
Unregistering an exit hook
This feature allows for the deregistration of an exit hook. The code sample shows how to register an exit hook and then later unregister it, preventing the callback from being called when the process exits.
const exitHook = require('exit-hook');
const unsubscribe = exitHook(() => {
console.log('Process is exiting');
});
// Later in the code, to unregister the hook
disconnect();
Other packages similar to exit-hook
signal-exit
signal-exit is a package that provides similar functionality to exit-hook, allowing you to run callbacks when a process exits. It differs in its implementation details and the breadth of exit signals it can handle, making it a good alternative depending on specific project requirements.
async-exit-hook
async-exit-hook extends the basic idea of exit-hook by adding support for asynchronous shutdown tasks. This can be particularly useful for ensuring that all asynchronous operations (e.g., database connections, file writes) are completed before the process exits.
exit-hook
Run some code when the process exits
The process.on('exit')
event doesn't catch all the ways a process can exit.
This package is useful for cleaning up before exiting.
Check out async-exit-hook
if you need async support.
Install
$ npm install exit-hook
Usage
const exitHook = require('exit-hook');
exitHook(() => {
console.log('Exiting');
});
exitHook(() => {
console.log('Exiting 2');
});
throw new Error('🦄');
License
MIT © Sindre Sorhus