Skip to content

Instantly share code, notes, and snippets.

@bbg
Created March 20, 2018 11:45
Show Gist options
  • Save bbg/9318a9a5ed3a00c1e6348f74d8509ac4 to your computer and use it in GitHub Desktop.
Save bbg/9318a9a5ed3a00c1e6348f74d8509ac4 to your computer and use it in GitHub Desktop.
nodejs dir to json
var fs = require('fs');
var path = require('path');
var diretoryTreeToObj = function(dir, done) {
var results = [];
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) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
diretoryTreeToObj(file, function(err, res) {
results.push({
name: path.basename(file),
type: 'folder',
children: res
});
if (!--pending)
done(null, results);
});
}
else {
results.push({
type: 'file',
name: path.basename(file)
});
if (!--pending)
done(null, results);
}
});
});
});
};
var dirTree = ('./');
diretoryTreeToObj(dirTree, function(err, res){
if(err)
console.error(err);
console.log(JSON.stringify(res));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment