I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function input()
or the C function gets
. Thanks.
To get the user's input from the web browser is easy by using JavaScript prompt() method. However, what is not understandable is using JavaScript which runs only the browser, to get input from a systems command line. Doing this is possible using NodeJS.
In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.
There are 3 options you could use. I will walk you through these examples:
(Option 1) prompt-sync: In my opinion, it is the simpler one. It is a module available on npm and you can refer to the docs for more examples prompt-sync.
npm install prompt-sync
const prompt = require("prompt-sync")({ sigint: true });
const age = prompt("How old are you? ");
console.log(`You are ${age} years old.`);
(Option 2) prompt: It is another module available on npm:
npm install prompt
const prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
if (err) { return onErr(err); }
console.log('Command-line input received:');
console.log(' Username: ' + result.username);
console.log(' Email: ' + result.email);
});
function onErr(err) {
console.log(err);
return 1;
}
(Option 3) readline: It is a built-in module in Node.js. You only need to run the code below:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With