简体   繁体   中英

NodeJS Stop and Start with Batch

I am trying to start and stop a nodejs app every n minutes on batch. This is what I have so far:

node index.js
pause

I think the way to do this is to use a for loop and wait n minutes, then stop the app. The problem is, how do I stop an nodejs app through batch?

I tried:

node index.js
sleep 30 //sleeps for 30 seconds
node index.js
sleep 30

The problem is, it will never get to sleep 30 seconds because my node js app never ends, therefore it will not go to the next line. Is there anyway to stop the program then continue with batch file.

I am talking about a .bat file.

If you want to force re-run all in index.js , you can try use bot.js (or any name you want) 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);

If you just want run code inside index.js , you can use loop function is the code you want re-run (because it is long to start with exec ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM