-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
Description
Version: v4.2.6
Platform: x86_64 GNU/Linux
I don't think this is a bug but some kind of advice would be nice in the documentation of process.on() in the future. Please, consider it.
If your script is structured following the design of a C program, chances are you may have a main loop similar to this:
while (true)
{
// Your program
}
If you suddenly need to do something on SIGINT, you may do this:
process.on("SIGINT", function () {
// remove incomplete output files because user interrupted the script with CTRL+C
process.exit();
});
while (true)
{
// Your program
}
This results in two issues:
1- As noted in documentation, node does not exit when you assign a listener to SIGINT, you must call process.exit() if you want to exit, but...
2- when you are inside the while loop, the event isn't triggered. Resulting in the script trapped in the loop and with no nice way of stopping. User must kill the process: close terminal, use Gnome System Monitor, send a SIGKILL (to node process) from pkill or similar commands.
I solved it and achieved the behavior I need by changing the while loop to this:
var interval = setInterval (function () {
// Your program
}, 0);
Similar to what you may do with javascript in client side code in a web browser to simulate a main loop.
This way, when user hits CTRL+C the event handler executes as expected.
This is not a bug, just how javascript code is executed, but if you don't know at the moment what happens when you register a listener for SIGINT you may expect that it works even while your program is inside a loop.
It took me a while to realize why CTRL+C wasn't working so I'm leaving this here.