NodeJS停止并开始批处理
我试图在每批n
分钟开始和停止nodejs应用程序。这是我到目前为止:
node index.js
pause
我认为这样做的方法是使用for
循环并等待n
分钟,然后停止应用程序。问题是,如何通过批处理停止nodejs应用程序?
我试过了:
node index.js
sleep 30 //sleeps for 30 seconds
node index.js
sleep 30
问题是,它永远不会睡30秒,因为我的节点js app永远不会结束,因此它不会进入下一行。无论如何停止程序然后继续批处理文件。
我在谈论一个.bat文件。
回答如下:如果你想在index.js
强行重新运行,你可以尝试使用bot.js
(或任何你想要的名字)child_process.exec:
const { exec } = require('child_process');
const loop = () => exec('node index.js', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
loop();
setInterval(loop, 30000);
如果你只想在index.js
中运行代码,你可以使用loop
函数是你想重新运行的代码(因为它很长,以exec
开头)。