How to read user input from terminal before pressing enter using node and javascript?

Viewed 341

How to read user input from terminal before pressing enter using node and javascript?

I have made a simple javascript application which uses process.stdin or readline to get user input, but I don't want the user to have to submit their input with enter/return. I'd like to read user input on keydown/keypress. Is this possible? How might I accomplish this? Thanks!

Requirements:

  • javascript, node
  • from terminal
  • user not required to submit string with enter/return

Prefer:

  • less libraries, more vanilla javascript
  • handles any key: letters, numbers, arrow keys, modifiers
1 Answers

An easy way to do it could be with the iohook package.

The native Node.JS way to do it would be like this.

require("readline").emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on("keypress", (char, evt) => {
  console.log("=====Key pressed=====");
  console.log("Char:", JSON.stringify(char), "Evt:", JSON.stringify(evt));

  if (char === "h") console.log("Hello World!");
  if (char === "q") process.exit();
});

The first line, require("readline").emitKeypressEvents(process.stdin) makes process.stdin emit keypress events, as it normally does not emit the event.

The second, process.stdin.setRawMode(true) makes process.stdin a raw device. In a raw device configured stream, key press events are emitted on a per character basis, instead of emitting per enter key press.

Then, the keypress event listener is added onto process.stdin to handle keypresses.

Note

When process.stdin is converted to a raw device, Ctrl+C does not emit a SIGINT signal, in other words, Ctrl+C will not stop the program. This means that you will need to manually bind a key to exit.

Related