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

问题描述 投票:0回答:1

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

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,它将显示文件的内容。

javascript node.js json express fs
1个回答
0
投票

可能在实际的IO读取发生之前正在执行test.findID(1),因此此时,问题尚未定义。

尝试使用fs.readFileSync代替fs.readFile。

© www.soinside.com 2019 - 2024. All rights reserved.