Get user input through Node.js console
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.
I will share 3 options you could use. So I will walk you through both 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!
I think this is a simpler option
npm install prompt-sync
const prompt = require("prompt-sync")({ sigint: true });
//With readline
const name = prompt("What is your name?");
console.log(`Hey there ${name}`);`enter code here`
This can also be done natively with promises. It is also more secure then using outside world NPM modules. No longer need to use callback syntax. Updating answer from @Willian. This will work with async await syntax and es6/7.
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
//usage inside aync function do not need closure demo only*
(async () => {
try{
const name = await prompt('Whats your Name: ')
//can use name for next question if needed
const lastName = await prompt(`Hello ${name} Whats your Last name?:` )
//can prompt multiple times.
console.log(name,lastName);
rl.close()
}catch(e){
console.errror("unable to prompt",e)
}
})()
//when done reading prompt exit program
rl.on('close', () => process.exit(0))