Thursday, 16 March 2017

node.js: setting global array from inside readFile

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?



via Harmonic

No comments:

Post a Comment