Athul Muralidharan
Athul Muralidharan

Reputation: 743

How to print the returned value of the function?

I am completely new to NodeJs and am trying to print the string that I have given in the return.

It is returning an empty String

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream("shopn'stop.txt")
});



function getText() {

var billString  = ""
lineReader.on('line', function (line) 
{
  // console.log('Line from file:', line);
  var tempStr = line;

  billString = billString.concat(tempStr + "\n");
  // console.log("temp " +  billString);
    });

 return billString;

}



console.log('BillString : ' +  getText());

How do I fix this ?

I am executing with Node filename.js

Current return :

BillString :

Upvotes: 1

Views: 861

Answers (1)

Nir Levy
Nir Levy

Reputation: 12943

NodeJs works asynchronously, which means that your console.log command starts right after the getText() command starts, but nothing assures you it will happen before it ends.

In order to print it, you need to put your console.log command inside the callback:

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream("shopn'stop.txt")
});

function getText() {

  var billString  = ""
  lineReader.on('line', function (line) {
    var tempStr = line;

    billString = billString.concat(tempStr + "\n"); 
  });

  console.log('BillString : ' +  billString);
}
getText();

Upvotes: 1

Related Questions