0

I want to take input in javascript program using cmd, as I am executing the js program using node through cmd, So how can I do it?

Aalexander
  • 4,987
  • 3
  • 11
  • 34
  • Did you remember to [search](https://stackoverflow.com/search?q=how+to+get+user+input+%5Bnodejs%5D) before posting? https://stackoverflow.com/questions/56842061/how-to-get-input-from-user-nodejs?noredirect=1&lq=1 – costaparas Feb 19 '21 at 06:36
  • Also, since you are using Node.js, the question should be tagged with [tag:nodejs] not just [tag:javascript]. – costaparas Feb 19 '21 at 06:36

1 Answers1

0

Short Answer: Use readline (built-in nodejs module)

Long Answer:

According to this blog Streams are the Node.js way of dealing with evented I/O - it's a big topic, and you can read more about them here. For now, we're going to use the built-in readline module which is a wrapper around Standard I/O, suitable for taking user input from command line(terminal).

Here's a simple example. Try the following in a new file:

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);
});
Aman Desai
  • 233
  • 2
  • 11