Step by step implementation:
Step 1: In the first step, we set up a NodeJs project environment. If you do have not installed NPM or NodeJs please refer to this article.
- Run the below command and initiate the NodeJs project.
npm init -y
Use “-y” to keep default answers to all questions.
Project Structure: After doing the above things move to create an index.js file for writing our code, and the directory looks like this.
.Step 2: Now we will see the working of the NodeJs readline module.
The readline module allows reading a data stream one line at a time. It can be included in the code with the require() method. We can enter any stream of data we want in the readline module, which allows us to work with standard input and output streams. Or the readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. It can be accessed using. The question method of the readline provides a facility to work a query-response mechanism we use the question method and pass two arguments first one is a query and the second one is a custom handler to take an argument as an input of the handler function.
Accepts the display query string and the callback function to be invoked as a response of the user’s input to the query. The createInterface method of the readline provides an interface object to work with readline and their methods.
Now let’s see the code implementation of the above approach. The below code shows the use of readline module for accepting input from the user as a CLI.
Step to run the application:
Explanation: The createInterface method is used to create an interface to take user input. It takes two parameters, the standard input (stdin) and standard output (stdout) of the current process. Next, the question() method of the createInterface object is used to prompt a question to the user. The second parameter is a callback function the will process the user’s input passed to it as a parameter. The logic inside the function will display an appropriate message based on the evaluation of the user’s input value. The process.exit() statement allows to exit the code else the interface will keep reading from the standard input.