5

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?

1
  • Are these child processes (i.e., you're starting the NodeJS process(es) you're trying to observe from within another app)? Commented Jun 1, 2016 at 15:01

2 Answers 2

6

The exit event 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(...);
});
Sign up to request clarification or add additional context in comments.

2 Comments

if you run a while(true){...} loop inside exit listener will it terminate ?
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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.