If this is possible I want to execute some command or script when one npm script is killed with CTRL + C. For example if gulp watch is interrupted. It is possible?
2 Answers
The
exitevent is emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler.
From Node.js process docs
To spawn some command synchronously, you could look into Synchronous Process Creation:
process.on('exit', code => {
require('child_process').spawnSync(...);
require('child_process').execSync(...);
require('child_process').execFileSync(...);
});
2 Comments
Jan Grz
if you run a
while(true){...} loop inside exit listener will it terminate ?Patrick Roberts
I wouldn't recommend doing that. If you did that then the thread would be stuck and you wouldn't be able to run asynchronous functions anyway.
If you have a custom script that you run through npm you can listen to the exit event of the process or child process. e.g.
process.on('exit', () => {
console.log('I am exiting....');
});
More info here