Search code examples
javascriptnode.js

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.


Solution

  • 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);
    });