我正在使用 Node-dev 开发 Node.js 应用程序。每次我保存应用程序的脚本(按 Control-S)时,node-dev 都会重新启动我的应用程序。现在的问题是,我能否检测到应用程序的重启,以便我可以在程序终止之前保存一些数据?
process.on('SIGINT', function() {
console.log('SIGINT');
});
上面的代码没有检测到这种重启。
我使用的是 Windows XP。
最佳答案
在您的 child 中,在 process
的 exit
事件上添加一个监听器:
process.on('exit', function() {
// Save application state
});
正如您从源代码中看到的,node-dev
派生以启动您的脚本。当一个文件更改时,父文件 launches its stop()
function , 等待 child 退出然后重新启动它:
child.on('exit', start)
stop()
stop()
function发送消息:
ipc.send({exit: true}, child)
ipc object使用 child.send()
method :
if (dest.send) dest.send(m)
node-dev
不能通过发送 SIGINT
信号来工作,但可以使用 IPC。看起来您可以通过在 message
event of process
上添加监听器来检测应用程序的重新启动。 ...但这不起作用(即 message
事件永远不会在 process
对象上发出)。我的猜测是 process.exit()
是同步的,我们的处理程序没有机会运行。
编辑 here是一个 Gist,其中包含在 Node 中使用 IPC 进行父/子通信的示例,如果有帮助的话。
关于javascript - node-dev下检测app重启,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20065428/