Registry / devops / node-cleanup

node-cleanup

JSON →
library2.1.2jsnpmunverified

The `node-cleanup` package provides a mechanism to install custom cleanup handlers that execute when a Node.js process exits. This includes normal termination (exit code 0), error-induced exits (uncaught exceptions, exit code 1), and receipt of POSIX signals such as SIGINT (Ctrl-C), SIGHUP, SIGQUIT, and SIGTERM. The current stable version is 2.1.2, released recently, following a "complete rewrite" in version 2.1.0. Its release cadence appears to be driven by feature enhancements and major architectural changes rather than strict time intervals. Key differentiators include support for multiple independent handlers, asynchronous cleanup for signals (allowing postponement of process termination), delegation of termination decisions to child processes (useful for scenarios with tools like Emacs), and custom `stderr` messages for Ctrl-C and uncaught exceptions. The library focuses on robust and reliable process shutdown management in various scenarios.

npm install node-cleanup
INSTALL
IMPORT
SIG · NODE-CLEANUP
N
node-cleanup
devopsjavascriptv2.1.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

nodeCleanup
const nodeCleanup = require('node-cleanup');
import nodeCleanup from 'node-cleanup';
This package is primarily designed for CommonJS. Direct ESM `import` might not work without specific Node.js module resolution configurations or transpilation for older versions. For most Node.js projects, use `require`.
nodeCleanup.uninstall()
nodeCleanup.uninstall();
import { uninstall } from 'node-cleanup';
`uninstall` is a method directly attached to the `nodeCleanup` function, not a named export. It removes all currently installed cleanup handlers.

This quickstart demonstrates how to install an asynchronous cleanup handler for POSIX signals like SIGINT (Ctrl-C), allowing critical data to be saved before the process fully terminates. It also configures custom `stderr` messages for signals and uncaught exceptions.

const nodeCleanup = require('node-cleanup'); let unsavedData = { data: 'some critical data', // Example data to save save: function(callback) { console.log('Saving unsaved data:', this.data); setTimeout(() => { this.data = ''; // Simulate data being saved callback(); }, 100); // Simulate async save operation } }; nodeCleanup(function (exitCode, signal) { if (signal) { console.log(`Received signal: ${signal}. Initiating async cleanup.`); unsavedData.save(function done() { // Important: calling process.exit() here would terminate immediately // and not inform the parent process of the signal. Re-emit the signal. process.kill(process.pid, signal); }); nodeCleanup.uninstall(); // Prevent handler from being called again on re-emitted signal return false; // Prevent immediate process exit to allow async work } console.log(`Exiting with code: ${exitCode}. Sync cleanup finished.`); }, { ctrl_C: "{^C} caught. Saving data...", // Custom message for Ctrl+C uncaughtException: "Uh oh. An uncaught exception occurred:" }); console.log("Process running. Press Ctrl+C to test async cleanup."); // Simulate some ongoing work to keep the process alive setInterval(() => { // This interval keeps the Node.js process from exiting naturally // until a signal or an uncaught exception occurs. }, 1000);
Debug
Known issues
breakingStarting with `v2.1.0`, default `stderr` messages for Ctrl-C and uncaught exceptions are no longer installed automatically when you only provide a cleanup handler. This changes the default behavior of earlier versions.
fix
To enable default `stderr` messages, either call `nodeCleanup()` with no arguments (`nodeCleanup();`) or explicitly pass an `stderrMessages` object, even if empty, when combining with a handler (e.g., `nodeCleanup(myHandler, {});`). To customize messages, provide them in the `stderrMessages` object (e.g., `nodeCleanup({ ctrl_C: 'My custom Ctrl-C message.' })`).
affects: >=2.1.0
gotchaWhen performing asynchronous cleanup operations in response to a signal, it is critical for the cleanup handler to return `false`. Failure to do so will result in immediate process termination, preventing your async tasks from completing.
fix
Ensure your signal cleanup handler explicitly `return false;` if you initiate asynchronous operations. Once cleanup is complete, re-emit the signal using `process.kill(process.pid, signal);` to properly terminate the process and inform the parent, rather than `process.exit()`.
affects: >=1.0.0
gotchaDelegating the decision to terminate to a child process (e.g., when a child intercepts SIGINT) requires careful management within the parent's cleanup handler to prevent premature exit.
fix
Implement logic within the parent's cleanup handler to check for active child processes (e.g., `if (child !== null && signal === 'SIGINT') return false;`) and only allow the parent to exit after the child has handled the signal or exited completely.
affects: >=1.0.0
Errors
Common errors & fixes
Process terminated immediately, my async cleanup function didn't finish.
The cleanup handler did not explicitly return `false` when performing asynchronous operations on signal reception, causing the process to exit before async work could complete.
fix
Modify your cleanup handler to include `return false;` when handling a signal and initiating async work. Once the async work is done, explicitly re-emit the signal using `process.kill(process.pid, signal);` to ensure proper termination.
SyntaxError: Cannot use import statement outside a module or ReferenceError: require is not defined
Attempting to use `require()` syntax in an ES Module context (`"type": "module"` in `package.json` or `.mjs` file) or vice-versa (using `import` in a CommonJS context). `node-cleanup` is primarily a CommonJS package.
fix
For `node-cleanup`, use `const nodeCleanup = require('node-cleanup');` in CommonJS modules. If you are in an ES Module context, consider using a dynamic import `import('node-cleanup')` or ensure your build system properly handles CommonJS interop.
Ctrl-C or uncaught exception messages are not appearing in stderr.
Since `v2.1.0`, `stderr` messages for `SIGINT` (Ctrl-C) and uncaught exceptions are no longer installed by default and must be explicitly configured.
fix
Explicitly configure `stderrMessages` when calling `nodeCleanup()`. For example, `nodeCleanup(myHandler, { ctrl_C: 'Custom Ctrl-C message' });` to set custom messages with a handler, or `nodeCleanup({ ctrl_C: 'Custom Ctrl-C message' });` if only messages are needed, or simply `nodeCleanup();` to get the default messages without installing a cleanup handler.
Upgrade
Version history
2.1.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
node-cleanup — npm install node-cleanup · libregistry