How to read keystrokes from stdin with Node.js?

Sometimes, we want to read keystrokes from stdin with Node.js.

In this article, we’ll look at how to read keystrokes from stdin with Node.js.

How to read keystrokes from stdin with Node.js?

To read keystrokes from stdin with Node.js, we can use the process.stdin method.

For instance, we write

const {
  stdin
} = process;

stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');

stdin.on('data', (key) => {
  if (key === 'u0003') {
    process.exit();
  }
  process.stdout.write(key);
});

to call setRawMode to true to let us listen to keystrokes.

Then we call resume to resume the parent process.

Next we call setEncoding to 'utf8' to set the encoding of the data we get from the 'data' event to 'utf8'.

Next, we call stdin.on with 'data' and a event handler callback to listen for the data event.

In the callback, we check if ctrl+c with key === 'u0003'.

If it’s true, we call process.exit to exit the program.

Otherwise, we call process.stdout.write to write the key value to the screen.

Conclusion

To read keystrokes from stdin with Node.js, we can use the process.stdin method.