For a small project of mine, I've been attempting to load JSON data. However, the issue arises when the loadDefs
function is executed before checking if file_data
has been modified.
loadDefs(file_path:any)
{
let file_data:string = '';
fs.readFile(file_path, 'utf8', (err, data:string) => {
if (err) {
console.error(err);
return;
}
file_data = data;
console.log(file_data);
});
if (file_data == '')
{
console.log("Data not loaded.");
return;
}
const loading_defs:Array<any> = JSON.parse(file_data);
console.log(loading_defs);
for (let index = 0; index < loading_defs.length; index++) {
const def = loading_defs[index];
if (def["type"] == "DefTypeDef")
{
this.defs[def["uuid"]] = {};
}
this.defs[def["type"]][def["uuid"]] = def;
}
}
The section where the function is called:
let g = new Game();
g.loadDefs("./Defs/defTypes.json")
Here is the output, including the contents of my "./Defs/defTypes.json" file:
Data not loaded.
[
{
"type": "DefTypeDef",
"uuid": "WorldObjectDef"
},
{
"type": "DefTypeDef",
"uuid": "NAME"
}
]
I had anticipated that the code would display the json file's content and load it in accordance with the defined logic.
During troubleshooting, I attempted to read the file externally and pass it into the function later on, but encountered the same problem. Different JSON files were also tried, each with unique content, yet none were successful. I am unsure how to ensure that my code executes as intended.