我有一个与Node.js和Express一起使用的简单Web应用程序。这是我的包结构:
我的questions.json
文件的内容如下:
[
{
"question": "What is your favorite color?",
"id": 1
},
{
"question": "How old are you?",
"id": 2
},
]
[operations.json
包含此:
var fs = require('fs');
const questions = 'public/questions.json';
class Operations{
constructor() {
fs.readFile(questions, (err, data) => {
if (err) throw err;
this.questions = JSON.parse(data);
});
}
findID(id) {
for (let key in this.questions) {
if (this.questions[key].id == id) {
console.log('found it!');
}
}
console.log("can't find it!...");
}
}
var test = new Operations();
test.findID(1);
此代码以前曾经可以使用,但现在由于某种奇怪的原因,它已损坏。 test.findID(1);
的输出始终返回can't find it...
,我不知道为什么。如果我在构造函数之外执行console.log(this.questions)
,则它始终会显示undefined
,但是如果我要在console.log(JSON.parse(data))
的回调函数中执行fs.readFile
,它将显示文件的内容。
可能在实际的IO读取发生之前正在执行test.findID(1),因此此时,问题尚未定义。
尝试使用fs.readFileSync代替fs.readFile。