Home > Article > Web Front-end > How to gracefully shut down a Node.js application
Node.js is an open source cross-platform runtime environment. It allows budding web developers to build efficient applications using simple JavaScript code. But in development, you need to consider how to gracefully shut down your Node.js application. In this article, we will discuss how to gracefully stop Node.js code.
The following is an example that demonstrates how to setup a Signal Handler handler:
function gracefulShutdown() { console.log("Node process stopping..."); // 停止Web服务器 server.close(() => console.log("HTTP server stopped")); // 关闭数据库连接 mongoose.connection.close(() => console.log("MongoDB connection closed")); // 结束Node进程 process.exit(0); } process.on("SIGTERM", gracefulShutdown); process.on("SIGINT", gracefulShutdown);
In this code snippet, when the SIGTERM and SIGINT signals are received, the gracefulShutdown function will be called. Complete the following actions:
Here is an example of using the forever module of Node.js:
var forever = require("forever"); var child = new (forever.Monitor)("app.js", { max: 3, //最多重启3次 silent: true, // 启动应用程序时,不显示输出到控制台的日志 args: [] }); // 在关闭应用程序之前执行以下操作 child.on("exit", function() { console.log("App has stopped"); }); // 启动并监视应用程序 child.start();
In this code snippet, the forever module can launch and monitor a Node.js application. If after four attempts to restart the application without success, the application will stop. If using this method, you should stop the forever module at the end to ensure that all processes on the server are closed.
Conclusion
In Node.js application development, stopping the application correctly is an important issue. Gracefully shutting down a Node.js application ensures that data is preserved, all resources are unaffected, and the running of other applications is not affected. This article provides four different methods, including using the Ctrl C shortcut key, creating a signal processing function, using the process.exit(0) method and using Node and npm modules. You can choose the method that best suits your needs to ensure your Node.js application stops gracefully.
The above is the detailed content of How to gracefully shut down a Node.js application. For more information, please follow other related articles on the PHP Chinese website!