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.
prompt
is an object methodwindow
in browsers. And what context would thisprompt
, Node or browser?– Cmte Cardeal
the context would be in Node
– Ravi Mughal
In this case, use some npm package to get to the same behavior expected in browsers. I recommend the prompt package
– Cmte Cardeal