const fs = require('fs').promises;
async function readMe(folder) {
let result = [];
try {
const content = await fs.readdir(folder, { withFileTypes: true });
for (let item of content) {
if (item.isDirectory()) {
await readMe(`${folder}/${item.name}`);
} else {
if (item.name === "sales.json") {
result.push(`${folder}/${item.name}`);
}
}
}
} catch (err) {
console.log(err);
}
return result;
}
async function main() {
const results = await readMe("stores");
console.log(results);
}
main();
I am trying to list the path to the sales.json inside the directories and sub directories of 'stores' folder.I am confused on why the above code doesn't give the expected result. While changing to this line inside the if statement :
result.push(... await readMe(`${folder}/${item.name}`) )
Makes the code work. If I encounter any sales.json file in my directories and sub-directories I am handling the path in the else statement .Then why do I need to again push it inside the if statement as well?
sales.jsonyou might have found in the current directory at that point. But the descending into the sub-folders, that happens via the recursive call inside the if-branch. And the result of that call, needs to get added to your result array as well - otherwise, it will get lost at this point, and not passed by to the previous level of the recursion.resultarray there - the one that you initialized as an empty array, right at the start of the method -let result = []. That is a different variable namedresult, than the one you have on the next higher "level" of call. If you read through the explanation in What is recursion and when should I use it?, things should become clearer, I think.