优雅地停止 Node.js

Stopping Node.js gracefully

如何优雅地停止Node.js应用程序?

我需要在接收到终止信号(例如,SIGINT (2), SIGTERM (3))时,在终止之前将我的内存内容写入文件,以便执行 "graceful shutdown"。怎么做?

PS。 这与 Quitting node.js gracefully 不是同一个问题,因为问题是错误的,做的是 ctrl+z 而不是 ctrl+c,并且答案不包括处理杀戮信号。

您可以使用

收听 exitSIGINT
process.on("exit", () => /* this will be called on the exit event */);


process.on("SIGINT", () => /* this will be called on the SIGINT event */);