To shut down a Node Express server gracefully when its process is killed, we use the '@moebius/http-graceful-shutdown
package.
For instance, we write
const express = require("express");
const GracefulShutdownManager =
require("@moebius/http-graceful-shutdown").GracefulShutdownManager;
const app = express();
const server = app.listen(8080);
const shutdownManager = new GracefulShutdownManager(server);
process.on("SIGTERM", () => {
shutdownManager.terminate(() => {
console.log("Server is gracefully terminated");
});
});
to create a GracefulShutdownManager
object.
Then we call shutdownManager.terminate
to shut down the Express app gracefully. when the SIGINT signal is received, which is when the Express process is killed.