【发布时间】: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