0

const fs = require('fs');
var students = [];
var programs = [];

module.exports.initialize = function(){
    return new Promise((resolve, reject) => {
        fs.readFile('./data/students.json', 'utf8',(err,data)=>{
            if(err) reject("Unable to read student data");
            students = JSON.parse(data);
        });
        console.log(students);
        fs.readFile('./data/programs.json', 'utf8',(err,data)=>{
            if(err) reject("Unable to read programs data");
            programs = JSON.parse(data);
        });
        console.log(programs);
        resolve("Both data read successfully");
    })
}

I don't know why this is happening but when the fs.readFile() function is done, both students and programs become empty. They are not empty when console.log() after JSON.parse() inside the readFile() function.

frowit
  • 33
  • 4
  • 1
    Modern JS note: don't use `var`, it's from a bygone era. Use `const` for variables that you don't ever want reassigned, and `let` for variables you do. As for the arrays becoming empty: they're already empty, and `resolve` does not wait for `fs.readFile` to finish (use `fs.promises` instead of `fs` so you can await async operations). – Mike 'Pomax' Kamermans Oct 01 '22 at 06:31
  • I would suggest requiring `fs/promises` and then making your function `async`. Then you can use code similar to `const data = await fsPromises.readFile('./data/students.json');` etc. to make it easier to write your async code. – Nick Parsons Oct 01 '22 at 06:39

0 Answers0