@push.rocks/smartexit

A library for managing graceful shutdowns of Node.js processes by handling cleanup operations, including terminating child processes.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

To install @push.rocks/smartexit, use pnpm:

pnpm install @push.rocks/smartexit

Usage

@push.rocks/smartexit helps Node.js applications run cleanup operations and terminate owned child-process trees during shutdown. SmartExit instances track resources; the application entry point opts into global signal and exception handling through ProcessLifecycle.

Basic Setup

import { ProcessLifecycle, SmartExit } from '@push.rocks/smartexit';

// Libraries can create trackers without installing process-global handlers.
const smartExit = new SmartExit({ processTerminationGraceMs: 1_000 });

// Call this once, from the application entry point only.
ProcessLifecycle.install();

Registering Cleanup Functions

Define custom async cleanup functions that execute before the process exits:

smartExit.addCleanupFunction(async () => {
  console.log('Closing database connections...');
  await database.close();
});

smartExit.addCleanupFunction(async () => {
  console.log('Flushing logs...');
  await logger.flush();
});

Managing Child Processes

Track spawned child processes so they get properly terminated on exit:

On POSIX, tree-wide termination requires each tracked child to be a detached process-group leader. addProcess() tracks the supplied PID; it does not discover an arbitrary non-detached process tree. Windows uses taskkill /T /F for the tracked root PID.

import { spawn } from 'node:child_process';

const childProcess = spawn('node', ['worker.js'], {
  // POSIX tree termination targets the group led by this child.
  detached: process.platform !== 'win32',
});
smartExit.addProcess(childProcess);

// Remove a simple worker after it and its owned tree have ended naturally.
childProcess.on('exit', () => {
  smartExit.removeProcess(childProcess);
});

Process integrations that expose a stable PID but are not Node.js ChildProcess instances can use the structural IProcessHandle contract. Pass the same object to removeProcess() that was registered with addProcess():

import { SmartExit, type IProcessHandle } from '@push.rocks/smartexit';

const smartExit = new SmartExit();
const processHandle: IProcessHandle = { pid: runtimeProcess.pid };

smartExit.addProcess(processHandle);
runtimeProcess.onExit(() => smartExit.removeProcess(processHandle));

When present, a process-handle PID must be a positive safe integer. A handle without a PID may be registered and removed by identity, but it does not establish PID ownership. On POSIX, removing a handle retains its PID while descendants still exist in the detached process group. An older handle cannot remove ownership that was replaced by a newer handle for the same PID.

The public processesToEnd map remains the backward-compatible registry of real Node.js ChildProcess instances. Structural handles are intentionally managed by the lifecycle registry without changing that map's published type.

Kill Process Trees by PID

Terminate an entire process tree using the static killTreeByPid method:

On POSIX, the PID passed to this static method must identify a detached process-group leader. On Windows, it is the root PID supplied to taskkill /T /F.

import { SmartExit, type TProcessSignal } from '@push.rocks/smartexit';

// Kill with default SIGKILL
await SmartExit.killTreeByPid(12345);

// Kill with a specific signal
await SmartExit.killTreeByPid(12345, 'SIGTERM');

A missing tree releases its PID from every registered SmartExit tracker. On POSIX, only successfully sending SIGKILL releases existing ownership; every other successfully sent signal retains ownership for later escalation. On Windows, every signal request uses forced taskkill /T /F, and a successful result releases ownership. Failures always retain ownership: POSIX rejects the call, while Windows keeps the established harmless-return behavior. A successful signal operation means that the OS accepted the signal, not that process death has already been observed.

trackedPids remains a mutable public Set<number> for compatibility. add(pid) establishes raw-PID ownership, delete(pid) withdraws one ownership, and clear() withdraws all ownerships. A withdrawal also removes matching retained ChildProcess entries and prevents an older in-flight graceful generation from escalating that PID later. Prefer addProcess() and removeProcess() for normal lifecycle management.

Triggering Cleanup Manually

You can trigger the same cleanup and process-tree termination pass manually:

const { processesKilled, cleanupFunctionsRan } = await smartExit.killAll();
process.exit(0);

processesKilled counts unique tracked roots or groups for which at least one termination operation succeeded. Concurrent killAll() calls share the same in-flight pass and result.

An application-level deadline can skip the remaining graceful interval and proceed to force escalation:

const terminationController = new AbortController();
setTimeout(() => terminationController.abort(), 5_000);

await smartExit.killAll({
  terminationSignal: terminationController.signal,
});

Do not call or await killAll() from a cleanup function registered on the same SmartExit instance. Such re-entry is rejected so shutdown cannot deadlock itself.

Integrating with Express

Gracefully close an Express server on shutdown:

import express from 'express';
import { ProcessLifecycle, SmartExit } from '@push.rocks/smartexit';

const app = express();
const smartExit = new SmartExit();
ProcessLifecycle.install();

const server = app.listen(3000, () => {
  console.log('Server running on port 3000');
});

smartExit.addCleanupFunction(async () => {
  console.log('Closing Express server...');
  await new Promise<void>((resolve) => server.close(() => resolve()));
});

Available Process Signals

The TProcessSignal type provides all standard POSIX signals:

import type { TProcessSignal } from '@push.rocks/smartexit';

// Examples: 'SIGINT', 'SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGUSR1', 'SIGUSR2', etc.

How It Works

When you create a SmartExit instance, it registers that tracker with ProcessLifecycle without installing process-global handlers. After the application calls ProcessLifecycle.install() once, the lifecycle manager:

  1. Handles SIGINT and SIGTERM by running registered shutdown work.
  2. Handles uncaught exceptions and preserves a non-zero exit code.
  3. Uses a synchronous force-kill safety net for process trees still tracked at final process exit.

On killAll(), it:

  • Executes registered cleanup functions before taking the process-tree snapshot.
  • On POSIX, sends SIGTERM to every snapshotted process group, waits one shared processTerminationGraceMs interval, then sends SIGKILL to exact groups that remain.
  • On Windows, uses one forced taskkill /T /F tree-termination phase.
  • Removes only successfully resolved snapshotted PIDs after escalation; failed force-kills and distinct PIDs registered during the grace interval remain tracked for a later pass or the exit safety net.
  • Cancels in-flight graceful intervals when ProcessLifecycle reaches its configured shutdown deadline.

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in license.md.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
A library for managing graceful shutdowns of Node.js processes by handling cleanup operations, including terminating child processes.
Readme
692 KiB
Languages
TypeScript 100%