Categories
JavaScript Answers

How to read keystrokes from stdin with Node.js?

Spread the love

To read keystrokes from stdin with Node.js, we can listen for keypresses with raw mode.

For instance, we write

const stdin = process.openStdin();
require("tty").setRawMode(true);

stdin.on("keypress", (chunk, key) => {
  process.stdout.write("Get Chunk: " + chunk + "\n");
  if (key && key.ctrl && key.name === "c") {
    process.exit();
  }
});

to set raw mode to true with setRawMode.

We open stdin with openStdin.

And we listen for the keypresses by calling on with 'keypress'.

We get the key pressed with key.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *