how to restart nodejs server code example

Example: nodejs restart process

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:

var spawn = require('child_process').spawn;

(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.