I am writing a Node.js utility for a bigger project that needs access to the file system. I am using the fs
module for this purpose. Due to the way that fs
works, I need a ton of nested functions in order to work.
I have an array at the second-highest scope (aka at the top of the function). I read the directory to get all folders/project names, then I loop over them using forEach
. Now using fs.readFile
, I read the JSON file that is present in all the directories. I append the data to the array then return the array at then end.
const get_projects = () => {
let projects = [];
fs.readdir(projectsPath, (err, files) => {
if (err) throw err;
files.forEach(file => {
fs.readFile(path.join(projectsPath, file, 'project.json'), { encoding: 'utf8'}, (err, data) => {
if (err) throw err;
const value = JSON.parse(data || "{}")
projects = [...projects, value];
})
})
})
return projects;
}
Now, for some reason (I expect it has something to do with scope), the function returns an empty array despite adding the data to the array.
I've tried replacing Array.push
by adding the value manually (as seen above). I've also tried converting the function to a class to make use of the this
keyword, using the fs/promises
library and callbacks (following the steps/instructions in the original question). No luck.