-2

I want to put the content of a file in an array. But when I try to access the variable fileArray it is empty after lineReader.on. This the code:

var fileArray=[]

    var lineReader = require('readline').createInterface({
      input: require('fs').createReadStream('file-to-read')  
    });

lineReader.on('line', function (line) {
  fileArray.push(line)
  //console.log(fileArray)  
});
// I want to get the array here but it is currently empty
console.log(fileArray)

Thanks

David
  • 311
  • 1
  • 4
  • 14
  • 1
    it is due to async nature of function, outside `console.log` runs before file is read that's why its empty – Zeeshan Hassan Memon Mar 12 '16 at 11:19
  • @ZeeshanHassanMemon, if that's true then writing the function in an IIFE would make it work? – Ray Mar 12 '16 at 11:22
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Amit Mar 12 '16 at 11:22

1 Answers1

2

The issue here is that lineReader.on('line', function () {}) is an event handler - i.e. the function you pass to it gets called asynchronously when the event takes place. However, this doesn't stop the rest of your code from executing - immediately after you define your lineReader event handler, the next line executes, before anything has been added to the array. To get the result you're after, your final console.log needs to be in a 'close' event handler - this will get called when the input stream hits the end.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85