【问题标题】:Setting global array from inside readFile [duplicate]从 readFile 内部设置全局数组 [重复]
【发布时间】:2017-08-07 22:51:47
【问题描述】:

我可能在这里遗漏了一些简单的东西,但由于某种原因,当我从函数内部设置数组的值时,一旦离开该函数,我就无法再读取该数组。

    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]")
    }

我在这里缺少什么?我假设与我声明数组的方式有关?

【问题讨论】:

  • fs.readFile 是异步的。请改用fs.readFileSync
  • @ajaiJothi Bingo!不好意思,我没注意到,谢谢!

标签: javascript jquery arrays node.js


【解决方案1】:

这是一个时间问题。 fs.readFile 是一个异步操作 - 在 fs.readFile 开始运行并且您的 threadArray 尚未填充后,您的第二个不起作用的 console.log 将立即得到处理。你可以改用fs.readFileSync

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);
}

【讨论】:

  • 哇哦。我不敢相信我做到了;你是绝对正确的。谢谢!
  • 很高兴我能提供帮助 :-)
猜你喜欢
  • 2016-02-10
  • 2012-12-12
  • 2021-11-06
  • 1970-01-01
  • 2023-03-04
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多