Node.js 中的 fs readFile 代码以某种方式损坏

fs readFile code in Node.js somehow broke

我有一个与 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); 的输出总是 returns can't find it... 我不知道为什么。如果我在我的构造函数之外执行 console.log(this.questions),它总是打印 undefined,但如果我在 fs.readFile 的回调函数内部执行 console.log(JSON.parse(data)),它将显示内容文件。

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

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