Universal Process Unload Handler

2.4.1 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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'); });

view raw JSON →