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.