I Know how to convert the directory structure into JSON object, from here
But I want all the files in an array, and the folders in object with the object key as the folder name. I have been trying for a long time but just cannot get it done.
Thi is what I have tried so far:
var diretoryTreeToObj = function (dir, done) {
var results = {};
var _contents = [];
fs.readdir(dir, function (err, list) {
if (err) {
return done(err);
}
var pending = list.length;
if (!pending) {
return done(null, {name: path.basename(dir), type: 'folder', children: results});
}
list.forEach(function (file, index) {
file = path.resolve(dir, file);
fs.stat(file, function (err, stat) {
if (stat && stat.isDirectory()) {
diretoryTreeToObj(file, function (err, res) {
results[path.basename(file)] = {
name: path.basename(file),
type: 'folder',
path: path.dirname(file),
_contents: [res]
};
if (!--pending) {
done(null, results);
}
});
} else {
results['_contents'] = [{
name: path.basename(file),
path: file
}];
if (!--pending) {
done(null, results);
}
}
});
});
});
};
Thanks in advance. :)