David
David

Reputation: 3441

Proper approach to code in node to catch SIGINT and other signals?

I'm a novice with node and javascript, and I'm more familiar with the old paradigm of synchronous programming rather than use of callbacks, promises, etc. in asynchronous programming offered in node and browser based javascript.

I was adding catching of SIGINT to some node scripts I was developing and noticed some peculiarity. I have a variety of node utility scripts. One is an express.js based app to serve stuff over HTTP. Another is a kafka message subscriber that processes messages coming to a specific topic on the bus. And a third one is a simple test/debug script for trying out node.

The express & kafka scripts handle SIGINT fine and terminate when the signal comes. But the simple debug script doesn't and continues operation even though I've sent Control + C (or D). So my question is, how should a novice write basic node code, when not using frameworks like express or a node kafka client that will already support this, to properly catch SIGINT? Here's my sample code below. Please suggest how to re-work (or encapsulate the relevant code for) it to catch the signal. As you can see, it's very basic code that a novice would likely write, like a hello world demo.

var sleep = require('sleep');

process.on('SIGINT', function() {
    console.log("Performing graceful shutdown");
    process.exit();
});

while(true){
    console.log("running "+new Date());
    sleep.sleep(1);
}

Upvotes: 1

Views: 415

Answers (1)

zangw
zangw

Reputation: 48536

Node.js can't handle any event if the event loop is blocked.

The while(true){} in your codes will block the event loop, and all SIGINT will be queued in the event queue, it cannot be handled until the while breaks.

About event loop, please refer to this video.

Upvotes: 1

Related Questions