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
.