Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda