Node JS – Reading command line input

In languages like c++,  java we can take command line input from user using standard i/o libraries. But JavaScript is used in browser and we never need to take input from user on command line, here Node JS fills the gap using its own libraries know as modules.

For reading input stream from command line Node JS has a l module known as ‘ReadLine’.  For using ‘ReadLine’ module we need to include this module in our code so we can use its functionality.

var rl = require(‘readline’);

‘ReadLine’ module will return an object so we can access its functionality.  Now we will use this object to create an interface that will be used to interact with input stream.

var interface = rl.createInterface(process.stdin, process.stdout, null);

stdin is out standard input and stdout is our standard output here. Now we can invoke method for input stream. interface has got a nice method for taking input, know as question method that prompts a message to user for input. Question method has a callback function
that is used to take user input. We can then use this input in put code.

interface.question(“What is your name?”, function(answer){

console.log(“Welcome “+answer +’!’);

});

As we will take input we need to close the interface and destroy stdin otherwise prompt will never end.

interface.close();

process.stdin.destroy();

Complete code is below

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.