I am trying to push an object to an array, from within a for loop. The array appears empty in the end. When I console.log() the data I am attempting to push, it appears to be correct. The purpose of this code is to read JSON from a file, use the data from this to create an object and add this object to an array. The reason I am using an array and loop, is so that I can repeat this process for multiple files. Then I will save the final array with all the objects to a single file.
I am doing this in Node.JS
This is my code so far:
const fs = require('fs')
const create_data = async (number) => {
let finished_data = []
for(let i = 1; i <= number; i++){
const path = "./generated_images/" + i + "/output.json"
fs.readFile(path, 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
let obj = JSON.parse(data);
finished_data.push({
id: obj.id,
img_url: obj.public_url,
})
}
});
}
return finished_data
}
create_data(5).then(res => {
console.log(res)
}) // I am just logging the data, eventually I will put an fs.writeFile() here, to write the array of objects to a file.