我试图每n
分钟批量启动和停止一个nodejs 应用程序。这是我到目前为止所拥有的:
node index.js
pause
我认为执行此操作的方法是使用 for
循环并等待 n
分钟,然后停止应用程序。问题是,如何通过批处理停止nodejs应用程序?
我尝试过:
node index.js
sleep 30 //sleeps for 30 seconds
node index.js
sleep 30
问题是,它永远不会休眠 30 秒,因为我的 Node js 应用程序永远不会结束,因此它不会进入下一行。是否有办法停止程序然后继续使用批处理文件。
我说的是 .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
function 是您想要重新运行的代码(因为以 exec
开头很长)。
关于node.js - NodeJS 批量停止和启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701488/