Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  71] [ 7]  / answers: 1 / hits: 31474  / 8 Years ago, sun, november 27, 2016, 12:00:00

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.


More From » node.js

 Answers
21

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.


[#59906] Thursday, November 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseg

Total Points: 460
Total Questions: 96
Total Answers: 90

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;