Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js process restart

I wanna know if theres a general function or can be made a function to restart the process; just like process.disconnect() but in this case it will restart the script when the function is called.

like image 240
Maxsanc1 Avatar asked Dec 04 '22 23:12

Maxsanc1


1 Answers

Generally process managers are used to (automatically) restart processes, such as monit, PM2, nodemon, forever, etc.

However, you could restart from the process itself by simply spawning a detached child process that waits some period of time and then executes the same script. You could do this as a combination of two commands, one to sleep and the other the current command line, or you could simply incorporate the sleep into your script. An example of the latter:

const { spawn } = require('child_process');

(function main() {
  if (process.env.process_restarting) {
    delete process.env.process_restarting;
    // Give old process one second to shut down before continuing ...
    setTimeout(main, 1000);
    return;
  }

  // ...

  // Restart process ...
  spawn(process.argv[0], process.argv.slice(1), {
    env: { process_restarting: 1 },
    stdio: 'ignore',
  }).unref();
})();

On Windows, you may need to add detached: true to your spawn() configuration object though. For *nix, this usually shouldn't be necessary.

One thing to keep in mind though is that any restarted process won't have access to the terminal anymore, if the original process was started in the foreground.

Also, you could eliminate the delay and process.env checking if your script does not use any resources that can only be used by at most one process at any given time.

One final note: if your process crashes abnormally, due to memory exhaustion, triggering a C++ assertion, a V8 bug, etc., your process won't restart obviously (even if you have an 'unhandledException' event handler set for process). To account for these situations you pretty much need some sort of external mechanism to restart the process.

like image 134
mscdex Avatar answered Jan 03 '23 20:01

mscdex