How to request user input in Node.js?

Asked

Viewed 102 times

2

I’m having trouble using the function prompt on Node.js. I intend to receive the value a user wants for verification and resolution of my code. But, when running the code, I get this error:

ReferenceError: prompt is not define

My code is:

var distance = prompt("Digite aqui a distância");

if (distance >= 6 && distance <= 800008) {
    console.log("distância aprovada");
}

If it is not possible to use the function prompt, which can replace?

  • 1

    prompt is an object method window in browsers. And what context would this prompt, Node or browser?

  • the context would be in Node

  • In this case, use some npm package to get to the same behavior expected in browsers. I recommend the prompt package

1 answer

5

Unlike browsers, exposing a function in the global object called prompt, Node.js does not implement it.

To request a user input, you can use the module readline, from Node.js. See an example:

const readline = require('readline');

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

rl.question('Qual o seu nome? ', (name) => {
  console.log(`Olá, ${name}!`);
});

Note that, unlike prompt, which is synchronous in browsers (and blocks the Event loop), the method question is asynchronous.

You can also convert this method to the promise interface using the function promisify, available in the module util. Thus:

const { promisify } = require('util');

// Utilize `question` com a interface de promessas...
const question = promisify(rl.question).bind(rl);

Note that I have omitted the definition of rl, which has already been demonstrated in the first example.


One curiosity is that the Deno, unlike Node.js, implements prompt (see here). This is probably due to the fact that Deno attaches great importance to maintaining greater compatibility with the standards already established on the web.

  • 2

    And you can use the AbortController to add a timeout, as soon as a setTimeout (for example) passes the time, run the .abort(), although it has nothing to do with the basic need of the question, just to mention it.... Other than that it is also interesting to add the SIGINT (rl.on('SIGINT', ....);) to control when there is a Ctrl+C

Browser other questions tagged

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