Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Serket Avatar asked Apr 23 '20 18:04

Serket


People also ask

Can JavaScript take input from console?

To get the user's input from the web browser is easy by using JavaScript prompt() method. However, what is not understandable is using JavaScript which runs only the browser, to get input from a systems command line. Doing this is possible using NodeJS.

How do you take input from user in JavaScript?

In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.


1 Answers

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

Enjoy!

like image 170
Willian Avatar answered Sep 16 '22 22:09

Willian