0

I'm probably missing something simple here, but for some reason, when I set an array's value from inside a function, I can no longer read that array once outside of that function.

    var threadArray = []; 

    function getThreads() {
      var fs = require('fs');        
      // read list of threads
      fs.readFile('./database/threadList.txt', function(err, data) { 
        var threadIds = data.toString().split("\n");    
        for(i in threadIds) { threadArray[i] = threadIds[i].split(","); } 
        console.log("This works: " + threadArray[0])
      }) 
      console.log("This does not work: " + threadArray[0] + " Returns [undefined]")
    }

What am I missing here? I'm assuming something to do with the way I declared the array?

Liam
  • 27,717
  • 28
  • 128
  • 190
Harmonic
  • 367
  • 1
  • 3
  • 18

1 Answers1

1

This is a timing issue. fs.readFile is an asynchronous operation - your second console.log that doesn't work is getting processed immediately after fs.readFile starts running and your threadArray is not yet populated. You can use fs.readFileSync instead

try {
  var threads = fs.readFileSync('./database/threadList.txt');
  var threadIds = threads.toString().split('\n');
  for(i in threadIds) { 
     threadArray[i] = threadIds[i].split(","); 
  } 
  console.log("This works: " + threadArray[0]);
} catch (e) {
  console.error("Error reading file: ", e);
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50