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.
Advertisement
Answer
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.
JavaScript
x
2
1
npm install prompt-sync
2
JavaScript
1
4
1
const prompt = require("prompt-sync")({ sigint: true });
2
const age = prompt("How old are you? ");
3
console.log(`You are ${age} years old.`);
4
(Option 2) prompt: It is another module available on npm:
JavaScript
1
2
1
npm install prompt
2
JavaScript
1
16
16
1
const prompt = require('prompt');
2
3
prompt.start();
4
5
prompt.get(['username', 'email'], function (err, result) {
6
if (err) { return onErr(err); }
7
console.log('Command-line input received:');
8
console.log(' Username: ' + result.username);
9
console.log(' Email: ' + result.email);
10
});
11
12
function onErr(err) {
13
console.log(err);
14
return 1;
15
}
16
(Option 3) readline: It is a built-in module in Node.js. You only need to run the code below:
JavaScript
1
18
18
1
const readline = require("readline");
2
const rl = readline.createInterface({
3
input: process.stdin,
4
output: process.stdout
5
});
6
7
rl.question("What is your name ? ", function(name) {
8
rl.question("Where do you live ? ", function(country) {
9
console.log(`${name}, is a citizen of ${country}`);
10
rl.close();
11
});
12
});
13
14
rl.on("close", function() {
15
console.log("nBYE BYE !!!");
16
process.exit(0);
17
});
18
Enjoy!