Read user input without using the prompt function

0

The only way to assign a value to a variable by the user in JavaScript is to use the prompt function 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'm running my JavaScript codes on the node.js terminal and it does not accept the prompt function.

    
asked by anonymous 30.09.2018 / 18:57

1 answer

1

In Node.js you can use the 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 as follows:

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.

Free translation:

  

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

    
30.09.2018 / 21:06