Registry / web-framework / unload

unload

JSON →
library2.4.1jsnpmunverified

The `unload` package provides a unified API for executing code reliably when a JavaScript process or environment is about to exit or unload. It abstracts away environment-specific mechanisms like `process.on('beforeExit')`, `process.on('SIGINT')`, `process.on('uncaughtException')` in Node.js, and `window.addEventListener('beforeunload')` or `window.addEventListener('unload')` in browsers, Electron, React Native, workers, and iframes. This ensures the registered exit functions are called only once, regardless of how the environment terminates. The current stable version is 2.4.1. It is particularly useful for library authors who need to clean up resources consistently across diverse JavaScript runtimes, ensuring robust shutdown procedures. It differs from simply using `process.on('exit')` by also handling abnormal terminations like `SIGINT` and `uncaughtException` in Node.js, and browser tab/window closures.

npm install unload
INSTALL
IMPORT
SIG · UNLOAD
U
unload
web-frameworkjavascriptv2.4.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
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 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

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

add
✓ import unload from 'unload'; unload.add(() => { console.log('Exiting'); });
✗ const unload = require('unload'); unload.add(function() {}); // CommonJS style, still works but ESM is preferred in modern codebases unless targeting Node.js only.
removeAll
✓ import unload from 'unload'; unload.removeAll();
To clear all previously registered unload handlers. Commonly used in testing or when dynamically managing lifecycle.
UnloadReturnType
✓ import unload, { UnloadReturnType } from 'unload'; const handler: UnloadReturnType = unload.add(() => {});
Type import for the return value of `unload.add()`, which contains the `remove` method. Useful for TypeScript projects.

Registers a cleanup function to run on process exit, demonstrates adding and removing handlers, and shows how it's used with TypeScript.

import unload from 'unload'; const cleanupFunction = () => { console.log('Performing cleanup before exit...'); // Simulate some asynchronous cleanup, though unload handlers should ideally be synchronous // or complete very quickly to avoid delaying process termination. try { // For example, flushing logs or closing database connections // In a real app, you might close a database connection here: // myDatabase.close().then(() => console.log('DB closed')).catch(err => console.error('DB close error', err)); console.log('Cleanup complete!'); } catch (error) { console.error('Error during cleanup:', error); } }; const handler = unload.add(cleanupFunction); console.log('Unload handler registered. Try Ctrl+C or closing the browser tab/window.'); // To demonstrate removal after some time (e.g., in an SPA where a component unmounts) setTimeout(() => { handler.remove(); console.log('Unload handler removed after 5 seconds.'); unload.add(() => console.log('A new handler added after removal, will run.')); }, 5000); // Simulate an uncaught exception in Node.js to see if handler runs // process.nextTick(() => { throw new Error('Simulated uncaught exception'); });
Debug
Known issues
gotchaUnload handlers, especially in browsers, should execute quickly and synchronously. Asynchronous operations may not complete before the environment terminates, potentially leading to data loss or incomplete cleanup. In Node.js, handlers are generally more robust but still prefer quick execution.
fix
Ensure cleanup logic is as fast as possible. For critical async tasks, consider handling them earlier in the application lifecycle or logging potential failures for post-mortem analysis.
affects: >=1.0.0
gotchaThe `unload` package guarantees handlers run only once. However, if multiple libraries or parts of an application independently add handlers, the order of execution is not guaranteed, and handlers should not rely on the side effects of other handlers.
fix
Design handlers to be idempotent and self-contained. Avoid inter-dependencies between different `unload.add()` calls.
affects: >=1.0.0
breakingWhile the README uses `var unload = require('unload');`, the package now primarily encourages ESM imports. Although CommonJS `require` still works, modern TypeScript and Node.js projects should use `import unload from 'unload';`.
fix
Migrate CommonJS `require('unload')` statements to ESM `import unload from 'unload';` for better tree-shaking and future compatibility in modern environments.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: unload.add is not a function
Attempting to call `add` on an `unload` object that was not correctly imported or initialized, often when mixing CJS and ESM, or if `unload` was destructured incorrectly.
fix
Ensure `unload` is imported as a default export: `import unload from 'unload';` for ESM, or `const unload = require('unload');` for CommonJS. Do not try `import { add } from 'unload';` as `add` is not a named export directly.
ReferenceError: unload is not defined
The `unload` package has not been imported or required in the current scope.
fix
Add `import unload from 'unload';` at the top of your ESM file or `const unload = require('unload');` for CommonJS files where `unload` is used.
Module not found: Can't resolve 'unload'
The `unload` package is not installed or the module resolver cannot find it.
fix
Run `npm install unload` or `yarn add unload` to install the package. Verify that your build configuration (webpack, Rollup, etc.) correctly resolves `node_modules`.
Upgrade
Version history
2.4.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
18 hits · last 30 days
node
16
Amazon
1
OpenAI (training)
1
Resources
unload — npm install unload · libregistry