1

I have found some "press any key to continue" in nodejs, but I am unable to get the key that was pressed:

press any key to continue in nodejs

I also found some readline, but this needs to have enter key pressed.

I am looking for a solution that will wait for a single press key and returns the value of the pressed key

Like:

let key = await waitKeyPressed(); 
console.log("You pressed key:", key);
yarek
  • 11,278
  • 30
  • 120
  • 219
  • The linked question is hooking the `data` event emitted by `process.stdin`, which should return either a `Buffer` or a `string` to the attached callback - what’s the issue of modifying the callback to read the value you’re after? – esqew Apr 03 '22 at 15:41
  • Just listen for the "data" event on stdin: `process.stdin.on("data", (chunk) => {});` Its not clear what you want or for what key you wait... – Marc Apr 03 '22 at 22:34

1 Answers1

1

Saw this question to see if there was something for easy copypastaing, turns out there wasn't, so I'll answer it now!

function waitKeyPressed() {
    return new Promise(resolve => {
        const wasRaw = process.stdin.isRaw;
        process.stdin.setRawMode(true);
        process.stdin.resume();
        process.stdin.once("data", (data) => {
            process.stdin.pause();
            process.stdin.setRawMode(wasRaw);
            resolve(data.toString());
        });
    });
}
  • setRawMode(true) allows us to get single key presses instead of waiting for a \n
  • process.stdin.resume() makes the event listener work
  • process.stdin.pause() stops listening to stdin, so your program can exit cleanly afterwards
ARitz Cracker
  • 77
  • 1
  • 4