UNPKG

exit-signal

Version:

A Node.js library for handling graceful process exits and shutdown signals.

67 lines (64 loc) 1.99 kB
/** * A utility type for handling both synchronous and asynchronous values. */ type MaybePromise<T> = T | Promise<T>; /** * Function signature for signal handlers. * * @param {exitCode} number - The exit code received by the process. * @returns {MaybePromise<any>} - A possible promise to handle async cleanup. */ type SignalHandler = (exitCode: number) => MaybePromise<any>; /** * Options for configuring an exit hook. */ interface ExitOptions { /** * The number of milliseconds to wait before forcefully exiting the process. * @default Infinity */ timeout?: number; } /** * A function that removes a registered exit hook when invoked. */ interface UnsubscribeFn { (): void; } /** * Registers an exit handler that will be called when the process is terminating. * The handler receives the exit code and can perform synchronous or asynchronous cleanup. * * @param handler - The function to execute on exit. Receives the process exit code. * @param options - Optional configurations for the exit hook, such as a timeout in milliseconds. * @returns A function to unsubscribe and remove the registered exit hook. * * @example * ```ts * import { onExit } from 'exit-signal'; * * // Register a cleanup handler * const unsubscribe = onExit(async (code) => { * console.log(`Cleaning up before exit with code ${code}`); * await cleanupResources(); * }, { timeout: 3000 }); * * // Later, if needed, remove the hook * unsubscribe(); * ``` */ declare function onExit(handler: SignalHandler, options?: ExitOptions): UnsubscribeFn; /** * Initiates a graceful exit by triggering the exit handlers and exiting with code 0. * This is equivalent to sending a SIGINT signal programmatically. * * @example * ```ts * import { gracefullyExit } from 'exit-signal'; * * // Trigger all registered exit hooks and exit with code 0 * gracefullyExit(); * ``` */ declare function gracefullyExit(): void; export { gracefullyExit, onExit };