Gracefully handle your modular NodeJS application's shutdown (termination), using dependencies.
Process signals captured: SIGINT
, SIGTERM
, SIGQUIT
.
Example
It doesn't matter in which order and where you define these graceful handlers, node-graceful-shutdown
will
handle them appropriately and exit the process once all of them are processed.
import { onShutdown } from "node-graceful-shutdown";
onShutdown("http-server", async function () {
});
onShutdown("message-bus", ["http-server"], async function () {
});
onShutdown("database", ["http-server", "message-bus"], async function () {
});
Or, if you have all your modules as exports and they all shutdown one after another,
this will work at its best in your application's main.js
:
import { onShutdown } from "node-graceful-shutdown";
import {
startModule1,
startModule2,
stopModule1,
stopModule2 ,
} from "./src";
export const startMyApp = async () => {
await startModule1();
await startModule2();
};
export const stopMyApp = async () => {
await stopModule1();
await stopModule2();
};
onShutdown(stopMyApp);
Features and Guidelines
This library, along existing ones, allow your application to be modular. You define a cleanup callback in-place,
in the same module, where initialization happens. In addition, it allows specifying the order
Recommendations:
- Please, do not use this module in libraries (packages). It is intended for end applications only (see why in
5.
). - Once imported,
onShutdown
is application-wide (in terms of a single process), so the callbacks and their dependencies will see each other when imported from multiple files. - Circular shutdown handler dependencies will throw an error immediately once declared.
- There's also an
onShutdownError
export which takes an error as an argument when any of assigned shutdown handlers throw an error (added for very-very prudent programmers only). - Importing this module deletes existing handlers (
SIGINT
, SIGTERM
, SIGQUIT
) if there are any. This is intended as other custom handlers can exit the process at any time. - You may also consider defining constants in your application, instead of string arguments (names).
Licence
MIT © Nikita Savchenko