在某些情况下,我可以永远防止重新启动我的节点脚本吗?
我有一个节点脚本,我永远从命令行运行: forever index.js
当脚本崩溃时,我想永远重新启动它,但不是所有的时间。 我知道某些情况需要人工干预才能解决。 在这种情况下,我希望能够以一种永远不会重新启动的方式退出这个过程。
有没有办法做到这一点?
我原本以为我可以用process.exit(1)
重新启动process.exit(0)
,不用process.exit(0)
重新启动,但显然情况并非如此。
这是另一种说法:
- 填写下面的代码中的空白。
- 将结果保存为index.js
- 用
forever index.js
启动脚本 -
该脚本应打印“你好”,退出,而不是重新启动
setTimeout(function () { console.log("hello") // YOUR CODE GOES HERE }, 1500)
顺便说一句,这里的延迟只是工作在默认的–minUpTime 1秒左右
永远支持使用–killSignal选项的退出信号定制:
--killSignal Support exit signal customization (default is SIGKILL), used for restarting script gracefully eg --killSignal=SIGTERM
以上是为了永久指示哪个杀手信号永远停止脚本开始。 要有select地停止运行一个脚本,基于脚本已经退出的方式,你需要使用forever-monitor 。
首先,你的脚本需要发送一个特定的信号,当你想永远不要重新启动它。 这是我们的script.js:
setTimeout(function () { console.log('hello'); //process.kill(process.pid, 'SIGKILL'); // this will cause forever to restart the script. setTimeout(function () { process.kill(process.pid, 'SIGTERM'); // this will cause forever to stop the script. }, 1000); }, 2000);
然后,我们需要一个带有永远监视器的脚本(我们称之为script-monitor.js ):
var forever = require('forever-monitor'); var child = new (forever.Monitor)('script.js', { max: 10, silent: false, args: [] }); child.on('restart', function() { console.error('Forever restarting script for ' + child.times + ' time'); }); child.on('exit:code', function(code) { console.error('Forever detected script exited with code ' + code); if (143 === code) child.stop(); // don't restart the script on SIGTERM }); child.start();
现在可以通过运行node script-monitor.js
来运行script.js
为了方便起见, 这里是 node.js 中的一系列信号事件。