我们有一个由 Upstart 管理的 node.js/express/socket.io 服务器。通过在 bash 中运行以下命令来停止服务器:“stop nodejs”,其中 Nodejs 是一个 Upstart 脚本,其内容如下:
#!upstart
description "node.js"
# Start the job
start on runlevel [2345]
# Stop the job
stop on runlevel [016]
# Restart the process if it dies
respawn
script
cd /var/www/node_server/
exec /usr/local/node/bin/node /var/www/node_server/chatserver.js >> /var/www/node_server/chatserver.log 2>&1
end script
post-start script
# Optionally put a script here that will notify you node has (re)started
# /root/bin/hoptoad.sh "node.js has started!"
end script
我们希望在服务器停止之前执行一些清理工作,如上所述。我们尝试了 process.on('exit' ... ) 和 process.on('SIGINT' ... ),但没有成功。
如何在服务器停止之前调用回调?
最佳答案
深入研究文档后,upstart 会触发 SIGTERM
信号来终止程序:
http://upstart.ubuntu.com/cookbook/#stopping-a-job
因此您可以使用 Node 收听此信号: https://nodejs.org/api/process.html#process_signal_events
SIGTERM is not supported on Windows, it can be listened on.
简短示例:
// Begin reading from stdin so the process does not exit.
process.stdin.resume();
// listen to the event
process.on('SIGTERM', () => {
console.log('some cleanup here');
});
这应该可以完成工作。
此外,您还有一个 pre-stop
upstart 事件,您可以在关闭服务之前手动关闭 Node ,以确保正确关闭 Node 。
关于node.js - 退出前清理node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702623/