我可能在这里遗漏了一些简单的东西,但由于某种原因,当我从函数内部设置数组的值时,我无法再在该函数外部读取该数组。
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
是一个异步操作 - 您的第二个不起作用的 console.log 在 fs.readFile
开始运行并且您的 threadArray
开始运行后立即得到处理code> 尚未填充。您可以使用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);
}
关于javascript - 从 readFile 内部设置全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42839588/