2016-11-20 73 views
2

我们有一个由Upstart管理的node.js/express/socket.io服务器。 “停止的NodeJS”,其中是的NodeJS包含以下内容新贵脚本:服务器通过在bash运行此命令停止在退出之前在node.js中清理

#!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'...),但都无济于事。

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

+0

你能否澄清'stop nodejs',你在哪里运行?你如何运行它? – Bamieh

+0

是的。请看我的新编辑。 –

回答

1

潜入文档后,新贵触发一个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 upstart事件,您可以在关闭服务之前手动关闭节点,以确保正确关闭节点。

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

+1

这个工程!谢谢。 –