0

I have a simple scenario of:

process.on("SIGINT", s => {
    console.log('trapped sigint:', s);
    signals.INT = true;
});

let i = 0;
while(true){
    if(signals.INT){
        console.log('got the SIGINT'); break;
    }
    console.log('process.pid:',process.pid, 'next val:', i++);
}

console.log('exited loop, done');
process.exit(0);

the problem is that once we are in the synchronous loop, we can't seem to handle any i/o events, even signals. Is there any way around this?

The only solution I can think of, while maintaining a synchronous loop, is to actually go into the guts of node and look for i/o events ourselves from the synchronous loop, but I severely doubt that this is exposed to users of the runtime.

Obviously, one way around this is to create an async loop, like so:

    process.on("SIGINT", s => {
        console.log('trapped sigint:', s);
        signals.INT = true;
    });
    
    let i = 0;
    (async () => {
        while(true){
          if(signals.INT){
            console.log('got the SIGINT'); break;
          }
          await console.log('process.pid:',process.pid, 'next val:', i++);
        }
    })()
    
    console.log('exited loop, done');
    process.exit(0);

that makes the loop a lot slower but allows us to capture i/o events. Is there any middle ground? I would love to be able to keep synchronous loop but still listen for i/o events somehow. I thought signals might be able to solve it, but I understand why even signals are not an exception in Node.js / JavaScript.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Sadly I believe this is the best answer still: https://stackoverflow.com/questions/34828541/interrupting-while-and-finalizing-gracefully-node-js – Alexander Mills Nov 19 '22 at 21:49

1 Answers1

0

Why don t you create an async loop externaly of your main loop that set a value to a variable that is global to both loop.

So when the loop run for one more loop it set the variable to the correct value?