Reputation: 17
I wrote a function which goes through directories and analyzes files in it but I don't know how to detect that the whole process is done (that it analyzed all files in all directories and sub directories) so I can do something with the result then.
I used recursion but I'm still learning it and I know it isn't quite right so I would like to ask for help.
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
let result = {};
const goThroughDirs = parentPath => {
const stat = fs.statSync(parentPath);
if (stat.isDirectory()) {
_.each(fs.readdirSync(parentPath), child => goThroughDirs(path.join(parentPath, child)));
} else {
analyseFile(parentPath)
.then(response => {
result = _.merge({}, result, response);
});
}
};
goThroughDirs(path.join(__dirname, 'rootDir'));
Thank you in advance for help.
Upvotes: 0
Views: 57
Reputation: 664444
Given that you are already using promises, it's as simple as
function goThroughDirs(parentPath) {
const stat = fs.statSync(parentPath);
if (stat.isDirectory()) {
return Promise.all(_.map(fs.readdirSync(parentPath), child =>
// ^^^^^^ ^^^^^^^^^^^ ^^^
goThroughDirs(path.join(parentPath, child))
)).then(responses =>
_.merge({}, ...responses);
);
} else {
return analyseFile(parentPath);
// ^^^^^^
}
}
goThroughDirs(path.join(__dirname, 'rootDir')).then(result => {
// it's done
console.log(results);
});
Upvotes: 1