Suppose I have the following code in node.js:
process.on('SIGTERM', function () {
process.exit(0);
});
for (var i = 0; i < 100; i++) {
console.error(i);
}
Will the code always print all the numbers up to 100?
This is easy enough to test:
process.on('SIGTERM', function () {
console.log('*** GOT SIGTERM ***');
process.exit(0);
});
process.kill(process.pid);
for (var i = 0; i < 100; i++) {
console.error(i);
}
The results show that, indeed, the for loop does run to completion, but this is misleading. The for loop blocks I/O. Because Node is single-threaded, process.exit(0) doesn’t get called until the for loop is done.
A more illustrative example:
process.on('SIGTERM', function () {
console.log('*** GOT SIGTERM ***');
process.exit(0);
});
process.kill(process.pid);
setTimeout(function() {
for (var i = 0; i < 100; i++) {
console.error(i);
}
}, 1000);
Here we use setTimeout to wait 1 second before doing the for loop. Node’s event loop will continue to run during that time, so the process.on('SIGTERM') will be called before the for loop begins. And the results are different: the for loop does not run at all.
Once process.exit(0) is called, the app ends and nothing else is executed. The difference between the two examples is when process.exit(0) is called.