User Input Using readline Module: Node.js


In this video tutorial we shall see how to gather user input and process it inside our node.js application.

In this application, we’ll be asking the user to enter his/her work experience and based on the user input we’ll do some logical processing and output appropriate result to the user.

readline Module
readline.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var rl = require('readline');
 
var prompts = rl.createInterface(process.stdin, process.stdout);
prompts.question("No of years you've been working in corporate?", 
                  function(experience){
 
 var msg = "";
 
 if( experience < 5 )
  msg = "You're short of "+(5-experience)+" years experience to 
         attend job interview at Apple Inc!";
 else
  msg = "Excellent, you're eligible for the job interview!!";
 
 console.log(msg);
 process.exit();
 
});

readline module is built into node.js to facilitate user input in node applications.

createInterface method is used to create an interface for user input.
createInterface method takes 2 parameters: process.stdin and process.stdout. These are standard input and standard output properties of the current process.

Using the createInterface object, we invoke question method.

question method takes 2 parameters:
First one being the question(something which is to be prompted to the user).
Second parameter is an anonymous function.

Response of the user is passed in as argument to this anonymous function.

Inside this anonymous function, we use some simple conditional logic and display the appropriate message to the user, based on his/her input.

i.e., if the person has less than 5 years of job experience, then he/she is not eligible to the job interview at Apple inc. If the job experience is greater than 5 years, then he/she is eligible!!

Finally, we display the content of msg variable using console.log
and exit from the process.

process.exit() is very important. If we don’t exit the process, the interface keeps reading from the standard input.

User Input Using readline Module: Node.js


[youtube https://www.youtube.com/watch?v=Y1TmesiVtGg]

YouTube Link: https://www.youtube.com/watch?v=Y1TmesiVtGg [Watch the Video In Full Screen.]



Output
node readline.js
No of years you’ve been working in corporate? 3
You’re short of 2 years experience to attend job interview at Apple Inc!

node readline.js
No of years you’ve been working in corporate? 9
Excellent, you’re eligible for the job interview!!

Note:
readline module is built into node.js because this is used most often in node applications.
User input is a crucial thing in any sophisticated application.

Leave a Reply

Your email address will not be published. Required fields are marked *