简体   繁体   中英

Access variable outside a function

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

The issue here is that lineReader.on('line', function () {}) is an event handler - ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM