2016-11-20 74 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

這個工程!謝謝。 –