Node.js进程重启 [英] Node.js process restart
问题描述
我想知道是否有通用功能,或者可以使它具有重新启动进程的功能;就像 process.disconnect()
一样,但是在这种情况下,它将在调用函数时重新启动脚本.
I wanna know if theres a general function or can be made a function to restart the process; just like process.disconnect()
but in this case it will restart the script when the function is called.
推荐答案
通常,进程管理器用于(自动)重新启动进程,例如monit,PM2,nodemon,forever等.
Generally process managers are used to (automatically) restart processes, such as monit, PM2, nodemon, forever, etc.
但是,您可以可以从进程本身重新启动,只需生成一个等待一段时间并执行相同脚本的分离的子进程即可.您可以将这两个命令组合在一起执行,一个命令进入睡眠状态,另一个则作为当前命令行使用,或者您可以将睡眠状态简单地合并到脚本中.后者的示例:
However, you could restart from the process itself by simply spawning a detached child process that waits some period of time and then executes the same script. You could do this as a combination of two commands, one to sleep and the other the current command line, or you could simply incorporate the sleep into your script. An example of the latter:
var spawn = require('child_process').spawn;
(function main() {
if (process.env.process_restarting) {
delete process.env.process_restarting;
// Give old process one second to shut down before continuing ...
setTimeout(main, 1000);
return;
}
// ...
// Restart process ...
spawn(process.argv[0], process.argv.slice(1), {
env: { process_restarting: 1 },
stdio: 'ignore'
}).unref();
})();
在Windows上,您可能需要将 detached:true
添加到您的 spawn()
配置对象中.对于* nix,通常通常不需要这样做.
On Windows, you may need to add detached: true
to your spawn()
configuration object though. For *nix, this usually shouldn't be necessary.
要记住的一件事是,如果原始进程是在前台启动的,那么任何重新启动的进程都将无法再访问终端.
One thing to keep in mind though is that any restarted process won't have access to the terminal anymore, if the original process was started in the foreground.
此外,您可以消除延迟,并通过 process.env
来检查脚本是否不使用在给定时间最多只能由一个进程使用的任何资源.
Also, you could eliminate the delay and process.env
checking if your script does not use any resources that can only be used by at most one process at any given time.
最后一点:如果由于内存耗尽,触发C ++断言,V8错误等原因导致进程异常崩溃,即使您的'unhandledException'<,/code>为
process
设置的事件处理程序.为了解决这些情况,您几乎需要某种外部机制来重新启动该过程.
One final note: if your process crashes abnormally, due to memory exhaustion, triggering a C++ assertion, a V8 bug, etc., your process won't restart obviously (even if you have an 'unhandledException'
event handler set for process
). To account for these situations you pretty much need some sort of external mechanism to restart the process.
这篇关于Node.js进程重启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!