Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!