How to get user input from command line with JavaScript

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. It will require us to use the readline() package. With this package, we can then accept user input and even output it to the console.

Syntax

readline.question(string, callback())

Parameters

string: This is normally a question or an interactive word that prompts the user to enter an input

callback(): This is a callback function or a call after function that accepts an argument which is the user’s input and does anything with it.

How to use the readline()

When you want to use the readline(), the first thing to do is to import the module:

const readline = require("readline")

The next is to create an interface for input and output operations.

const rl =
 readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

Now, we can proceed to use the .question() method as shown in the example below:

// import readline module
const readline = require("readline");
// create interface for input and output
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// create empty user input
let userInput = "";
// question user to enter name
rl.question("What is your name\n", function (string) {
userInput = string;
console.log("Your name is " + userInput);
// close input stream
rl.close();
});

When the code above is run, the output is as follows:

From the code above, the readline() module was required. We used it to create standard input and output interface. We then called the question() method on line 14. Then, the user input is passed to the userInput variable on line 15. We logged the user input on line 17.
Finally, we closed the stream with close() method on line 20.