JavaScript I/O using cmd

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?

1 thought on “JavaScript I/O using cmd”

  1. 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);
    });
    
    Reply

Leave a Comment