Reputation: 2843
I'm struggling with something in NodeJS. What I'm trying to do is just do read a directory and the subdirectories for files. Easy as it sounds, I'm stuck.. I tried a solution I found here on SO in another thread, but it doesn't seem to read the files from the subdirectories, only the first directory it reaches. The meaning of this function below was to load all controllers from a given directory.
let walk = function(dir) {
let results = [];
let items = fs.readdirSync(dir);
items.forEach(function(item) {
let currentItem = path.join(dir, item);
let stat = fs.lstatSync(currentItem);
if (stat && stat.isDirectory()) {
let dirName = path.parse(currentItem).name;
results[dirName] = results.concat(walk(currentItem));
} else {
let fileName = path.parse(currentItem).name;
results[fileName] = currentItem;
}
});
return results;
};
const Controller = walk('app/Http/Controllers');
The log looks like this
[ Auth: [],
Controller: 'app\\Http\\Controllers\\Controller.js',
HomeController: 'app\\Http\\Controllers\\HomeController.js'
]
The problem is that the folder Auth is read, but not the files in it. What am I doing wrong?
Upvotes: 0
Views: 40
Reputation: 1149
You want results to be an object or a Map, not an array.
let results = {};
An array is used to list elements, but in this case you want to map the filename to the file. An object is similar to a map, but the keys must always be strings (which is the case here).
Upvotes: 1