Reputation: 107
I have a simple web application that I am using with Node.js and Express. This is my package structure:
The contents of my questions.json
file are as follows:
[
{
"question": "What is your favorite color?",
"id": 1
},
{
"question": "How old are you?",
"id": 2
},
]
And operations.json
contains this:
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);
This code used to work before but now for some odd reason, it is broken. The output of test.findID(1);
Always returns can't find it...
And I cannot figure out why. If I do a console.log(this.questions)
outside of my constructor, it always prints undefined
, but if I were to console.log(JSON.parse(data))
inside the callback function of the fs.readFile
it will display the contents of the file.
Upvotes: 1
Views: 781
Reputation: 36
Probably test.findID(1) is being executed before the actual IO reading happens, so at that moment, questions is undefined.
Try using fs.readFileSync instead of fs.readFile. This should be actually be fine, as you are still within the constructor of the object.
Upvotes: 2