Skip to content

Instantly share code, notes, and snippets.

@kalisjoshua
Created September 14, 2012 00:05
Show Gist options
  • Save kalisjoshua/3718809 to your computer and use it in GitHub Desktop.
Save kalisjoshua/3718809 to your computer and use it in GitHub Desktop.
Directory as JSON object
var fs = require("fs");
var tree = function(dir, done) {
var results = {
"path": dir
,"children": []
};
fs.readdir(dir, function(err, list) {
if (err) { return done(err); }
var pending = list.length;
if (!pending) { return done(null, results); }
list.forEach(function(file) {
fs.stat(dir + '/' + file, function(err, stat) {
if (stat && stat.isDirectory()) {
tree(dir + '/' + file, function(err, res) {
results.children.push(res);
if (!--pending){ done(null, results); }
});
} else {
results.children.push({"path": dir + "/" + file});
if (!--pending) { done(null, results); }
}
});
});
});
};
module.exports = tree;
@Burnett01
Copy link

BEST!!!!!!

Copy link

ghost commented Nov 26, 2019

Thankz!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment