node.js - 退出前清理node.js

标签 node.js

我们有一个由 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 。

http://upstart.ubuntu.com/cookbook/#pre-stop

关于node.js - 退出前清理node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702623/

相关文章:

node.js - 将 Git 存储库迁移到 tfs Git,同时保留所有历史提交

javascript - 使用特殊字符对 UTF-8 中的单词中的句子进行标记

node.js - Nodemailer 和 GMail OAuth : Username and Password not accepted

node.js - 如何使用 API 网关集成访问 Node js AWS Lambda 中的 POST 参数?

sql - postgreSql “relation does not exist” 即使在 phpPgAdmin 中工作

javascript - node.js 和浏览器中的 jade 模板助手

node.js - 使用 package.json 在全局和本地安装依赖项

javascript - 重载的 typescript 函数参数不适用于 async 关键字

mysql - NodeJS Express 内连接问题

image - 添加并保存圆形蒙版框图像