How to Read DataStream with Node JS Readline Module

Last Updated on by in Node JS

This Node js Readline Module tutorial helps make your Node js knowledge prosperous. In this example tutorial i will propel node.js module info in your programming knowledge which is very helpful in reading the data stream.

The readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.
– Node

Read DataStream with Node JS Readline

Let’s begin this tutorial and generate a new file and name it readline.js. Now, we defined the nodeReadline const and imported readline service through the require method.

const nodeReadline = require('readline');

Initialize the readline process with createInterface() method.

var myInterface = nodeReadline.createInterface(process.stdin, process.stdout);

The Node js Readline Module evokes a wrapper around the ongoing process that we defined in the example. It adjoins the core functionality over its top, and the mechanism makes it easier to interpret.

Here is the example of a complete code that we need to read the data streamline in node js.

const nodeReadline = require('readline');
var util = require('util');

var myInterface = nodeReadline.createInterface(process.stdin, process.stdout);

myInterface.question('I am sure you must have a name? ', (name)=>{
    myInterface.setPrompt(`${name} What is your age? `);
    myInterface.prompt();
    myInterface.on('line', (age)=>{
        if(age<20)
        {
            util.log(`${name.trim()} as per your ${age}, you cannot go ahead`);
            myInterface.close();
        } 
        else {
            util.log(`${name.trim()} as per your age, you are good to go ${age}`);		
            myInterface.close();
        }
    })
});

Node JS Readline Methods

You can go ahead and try your hands on the following methods:

Method Description
clearLine() Helpful in clearing the existing line of the mentioned stream
clearScreenDown() Empties the named stream from the prevailing cursor down position
createInterface() It helps in producing an interface object
cursorTo() It helps in dealing with moving the cursor to the defined position
emitKeypressEvents() It triggers the keypress events for the named stream
moveCursor() It helps in moving the cursor to a brand new position, pertinent to the prevailing position

Eventually, we have completed this tutorial and you must have understood how to make a Node.js Command Line Interface program interactive with the help of predefined readline Node module.

I hope it will help you to read a file line by line in Node.js, please consider it sharing with others.