Erik Hermansen
Erik Hermansen

Reputation: 2379

SIGINT handler in NodeJS app not called for ctrl-C (Mac)

My code:

process.on('SIGINT', function() {
  console.log('Interrupted');
  process.exit();
});

// A big loop here that takes several seconds to execute through.

console.log('Exited without interruption');

I run the program from the command line, and while it is still running, press ctrl+C. I am immediately returned to the command line. However, the console.log('Interrupted') does not display in the output. After some time elapses, the console.log('Exited without interruption') is displayed, proving that the process did not exit when I hit ctrl+C, but instead kept running in the background after I was returned to the command line.

Removing the process.on() statement allows the process to exit when ctrl+C is pressed. (No 'Exited without interruption' is output.)

Have tried both the () => { and function() { function declaration styles with same result.

Mods, please do not too hastily mark this as a duplicate, although of course, I'm happy to be referred to an existing solution that works. I've seen Can't stop local node server with Ctrl + C (Mac) - the behavior in response to ctrl+C is different.

Upvotes: 5

Views: 8908

Answers (1)

Artur P.
Artur P.

Reputation: 896

// Begin reading from stdin so the process does not exit imidiately
process.stdin.resume();
process.on('SIGINT', function() {
  console.log('Interrupted');
  process.exit();
});

https://nodejs.org/api/process.html#process_signal_events

EDIT:

// A big loop here that takes several seconds to execute through.

This is your problem. NodeJS is single-tread. When you perform sync loop you blocks event-loop and other event listeners wont be able work at the same time.

You can:

  1. Make loop async (recursive function with process.nextTick())
  2. Spawn child-process (worker) for loop job, then main event-loop will wont be blocked

Upvotes: 9

Related Questions