1

Is possible to restart automatically a node cli script when it's finished to execute the code?

I have this cli script that will run until a variable reach a limit

const maxExecution = 200;
let i = 0;

let task = setInterval( () => {
  i++;   
  if( i >= maxExecution ){
    clearInterval(task);
  }
  // code here... 
},5000);

This code will work fine and will stop the tasks when the i variable reach the set limit. I'm reading this question about how to manage process.exit. Is there any event I can listen to understand if the script execution have reached the end?

newbiedev
  • 2,607
  • 3
  • 17
  • 65
  • 1
    Does this answer your question? [How can I restart a Node.js app from within itself (programmatically)?](https://stackoverflow.com/questions/9357757/how-can-i-restart-a-node-js-app-from-within-itself-programmatically) – jonny Apr 09 '21 at 08:32

1 Answers1

2

I had this code (typescript, not vanilla nodejs) when I was working with node<=10 (possibly between 6 ~ 10, not quite sure), it can restart itself on-demand:

import { spawn } from "child_process";

let need_restart:boolean=false;

process.on("exit",function(){
    if(need_restart){
        spawn(process.argv.shift(),process.argv,{
            "cwd":process.cwd(),
            "detached":true,
            "stdio":"inherit"
        });
    }
});

It's part of a http/ws server, when all server closed (no more event), the process automatically exit. By setting the need_restart to true, it will restart itself when this happen.

I haven't used node for quite some time, so I'm not sure if this still work on later version, but I think it's worth mentioning it here.

Passerby
  • 9,715
  • 2
  • 33
  • 50
  • I will give it a try, thank you for the suggestion. I'm writing a class to achive this beahviour with every script that will exit when the code execution is ended. I'm not sure if proceed with `spawn` or with `exec` function of node `child_process`. Any suggestion? – newbiedev Apr 09 '21 at 09:06
  • @newbiedev One of the key property here is `"detached":true`, which will allow current process to exit (and hence "restart"). From what I see, `exec` does not allow this option, so it may prevent the current process from stopping. This is critical in my situation, as I had to release ports I was listening to. – Passerby Apr 09 '21 at 09:25
  • I understand. I will do some tests to find the better function to use. At the moment I'm trying to restart the process and also to spawn multiple process of the same script. I'm unable to post a new question at the moment but every suggestion will be appreciated – newbiedev Apr 09 '21 at 09:46