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.
readline.question(string, callback())
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.
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 moduleconst readline = require("readline");// create interface for input and outputconst rl = readline.createInterface({input: process.stdin,output: process.stdout,});// create empty user inputlet userInput = "";// question user to enter namerl.question("What is your name\n", function (string) {userInput = string;console.log("Your name is " + userInput);// close input streamrl.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.