Hello.I have a simple Express server with a static folder containing JSON files. I want to read every JSON file and write it into an array and later send that array to my frontend.My code:router.get('/', (req, res) => { let jsonArray = [] fs.readdir(dir, (err, files) => { let jsonFiles = files.filter((file) => { if(file.includes('.json')) { return file } }) jsonFiles.forEach((filename) => { fs.readFile(`${dir}/${filename}`,(err, data) => { if(err) { return console.log(err); } else { let jsonData = JSON.parse(data) jsonArray += JSON.stringify(jsonData, null, 2) console.log(jsonArray) //outputs array 3 times for each json file } console.log(jsonArray) //outputs array 3 times for each json file }) console.log(jsonArray) //outputs empty array 3 times }) console.log(jsonArray) //outputs empty array once }) console.log(jsonArray) //outputs empty array once }) Why is jsonArray empty outside fs.readFile? If this is not the correct way of doing it, how can I achieve same result?Thanks.
Submitted July 02, 2020 at 09:19AM by Spxy
No comments:
Post a Comment