Georgi Naumov
Georgi Naumov

Reputation: 4201

NodeJS run command when script is terminated

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?

Upvotes: 5

Views: 2399

Answers (2)

Avraam Mavridis
Avraam Mavridis

Reputation: 8920

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

Upvotes: 1

Patrick Roberts
Patrick Roberts

Reputation: 51816

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(...);
});

Upvotes: 6

Related Questions