How can I programmatically shutdown a node program and restart it without using any libraries?
Asked Answered
G

1

2

I need to shutdown a node program and have it restart. I need to do this within the itself program without having to use something like forever needing to be setup.

I know I can use process.exit() to shut the program down, but anything I can think of that would open it back up that I can kick off from within node would be killed by process.exit() before it could finish. Is there a way I'm not seeing to detach a exec call from the process before I exit? Any other ideas? Do I have to suck it up and go use forever?

Gallon answered 22/10, 2013 at 12:23 Comment(3)
Possible duplicate: #9358257. Is there a particular reason you don't want to use forever?Gough
Possible duplicate of node.js app that can restart itselfClemons
I'm back 6 years later because this got marked as a duplicate. The linked question shows solutions up until 2017 that required other modules. When this question that asked for a solution to this problem without another module. As for why I didn't want to install forever, this was on an industrial embedded application that had to be deployed on multiple machines. I had limited repository space and didn't want to have to bring in another library and it's dependencies and capture them to keep subsequent changes from breaking my solution or necessitating quality testing to verify again.Gallon
C
2

Quick and dirty, not very well tested:

var child_process = require('child_process');

process.on('SIGINT', function() {
  console.log('restarting...');
  child_process.fork(__filename); // TODO: pass args...
  process.exit(0);
});

console.log('Running as %d', process.pid);

setTimeout(function(){}, 1000000); // just some code to keep the process running
Cursor answered 22/10, 2013 at 12:33 Comment(1)
This worked like a charm. Thanks so much! I got the way the node process was started from process.argv and just ran it again.Gallon

© 2022 - 2024 — McMap. All rights reserved.