gpt4 book ai didi

javascript - Node.js 中的 fs readFile 代码不知何故崩溃了

转载 作者:行者123 更新时间:2023-11-30 13:50:39 25 4
gpt4 key购买 nike

我有一个简单的 Web 应用程序,我正在使用 Node.js 和 Express。这是我的包结构:

enter image description here

我的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 的回调函数中,它将显示文件的内容。

最佳答案

可能 test.findID(1) 在实际 IO 读取发生之前被执行,所以在那一刻,问题是未定义的。

尝试使用 fs.readFileSync而不是 fs.readFile。这实际上应该没问题,因为您仍在对象的构造函数中。

关于javascript - Node.js 中的 fs readFile 代码不知何故崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58324812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com