Created
September 14, 2012 00:05
-
-
Save kalisjoshua/3718809 to your computer and use it in GitHub Desktop.
Directory as JSON object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BEST!!!!!!