在退出之前清理node.js

我们有一个由Upstartpipe理的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'…),都无济于事。

如何在服务器停止之前调用callback权限?

在深入文档后,暴发户发出一个SIGTERM信号终止程序: http : //upstart.ubuntu.com/cookbook/#stopping-a-job

因此您可以使用节点来监听此信号: https : //nodejs.org/api/process.html#process_signal_events

SIGTERM不支持在Windows上,它可以被侦听。

简短的例子:

 // 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暴发事件,您可以在closures服务之前手动closures节点,以确保正确closures节点。

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