Read user input without using the prompt function

Asked

Viewed 1,428 times

1

The only way to assign value to a user variable in Javascript is by using the function prompt or is there any other?

Because in Python, for example, we can do this:

numero = int(input("Informe um número: "))

I ask this because I am running my Javascript codes in the Node.js terminal and there does not accept the function prompt.

1 answer

1


In the Node.js you can use the module readline:

const readline = require('readline');

const input = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

input.question('Informe um número: ', (resposta) => {
  // TODO: Log the answer in a database
  console.log(`Número informado: ${resposta}`);
  input.close();
});

If you want to use async/await you can do it this way:

const readline = require('readline');

const input = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const perguntar = (pergunta) =>  new Promise(resolver => input.question(pergunta, (resposta) => resolver(resposta)));

const executar = async () => {
  console.time('Execução');

  try {
    const resposta = await perguntar('Informe um número: ');
    console.log(`Número informado: ${resposta}`);
  } catch (err) {
    console.log(err)
  }

  // Totaliza o tempo de execução
  console.timeEnd('Execução');
}

executar();

readline

The readline module provides an interface for Reading data from a Readable stream (such as process.stdin) one line at a time.

In free translation:

The readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.

  • The person responsible for the downvote can explain the reason that makes my answer wrong (despite the acceptance of the person who asked) why my answer would be wrong?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.