Reputation: 51
I'd like to run a process once another process exits.
For example, if I'm running a node JS file and I hit CTRL + C, it should close the current file and run another process from another JS file
Something like that (PSEUDO-CODE):
process.on('exit', () => {
console.log("exiting")
}).then( //I am conscious it's wrong to put like that
//open another js file and run this process
);
Upvotes: 5
Views: 2506
Reputation: 6757
No, this is not possible, because process
is a global object that represents the current Node.js process (read more about it in the official docs). When that process exits, your script is over, so there is no possibility to do anything after that.
However, you can run something from the place you are calling your Node.js script, because the caller may still be running after your script exited. This might be a bash script, another Node.js process, or something else.
Alternatively, you could spawn a new independent process within the callback of process.on('exit', () => {...})
like in the snippet below (read more about that in the official docs):
const spawn = require('child_process').spawn;
process.on('exit', () => {
const child = spawn('node', ['some_other_script.js'], {
detached: true,
stdio: 'ignore'
});
child.unref();
});
Strictly speaking, this is not "after" the process exits - it is before the parent process exits. I don't think it makes any difference in your example, though.
Upvotes: 5