Peter
Peter

Reputation: 11890

How to yield to keypress detection in nodejs?

In my nodejs application, I am doing some cpu-intensive work in a tight loop:

while(!isQuit) {
    doMyWork();
}

For the sake of explanation, doMyWork() is a simple method that writes random data into a file.

At the start of the code, I have added logic to check for keyboard press:

var isQuit = false;
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (str, key) => {
  if (key.name === 'q') {
    isQuit = true;
  }
});

The idea is to quit my processing when the user presses "q" on the keyboard.

The problem is that the keyboard presses are not being looked at. I think it is primarily because my tight loop is not giving a breather to the keyboard event processing.

Is there some function call I can make within my tight loop to yield for keyboard event processing?

Or, is there a way to rewrite my while loop such that doMyWork() keeps getting called asynchronously until the keypress event is received?

Upvotes: 2

Views: 553

Answers (1)

canon
canon

Reputation: 41675

Try an interval rather than a loop.

let handle = setInterval(function(){
  if (isQuit) {
    clearInterval(handle);
  } else {
    doMyWork();
  }
}, 1);

That should give stdin a chance to break into the event loop.

Upvotes: 2

Related Questions