-
-
Save Marak/395521 to your computer and use it in GitHub Desktop.
This file contains hidden or 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") | |
, path = require("path") | |
fs.tree = function (root, cb) { | |
fs.lstat(root, function (er, s) { | |
if (er) return cb(er) | |
s.name = root | |
// if it's a dir, then get the list of children. | |
if (!s.isDirectory()) return cb(null, s) | |
fs.readdir(root, function (er, children) { | |
if (er) return cb(er) | |
s.children = [] | |
var childrenWaiting = children.length | |
, index = 0 | |
, error = false | |
children.forEach(function (child) { | |
var i = index ++ | |
if (error) return | |
fs.tree(path.join(root, child), function (er, t) { | |
if (error) return | |
if (er) { | |
error = true | |
return cb(er) | |
} | |
t.name = child | |
s.children[i] = t | |
if (--childrenWaiting === 0) cb(null, s) | |
}) | |
}) | |
}) | |
}) | |
} | |
fs.treeSync = function (root) { | |
var s = fs.lstatSync(root) | |
s.name = root | |
if (!s.isDirectory()) return s | |
var children = fs.readdirSync(root) | |
s.children = [] | |
for (var i = 0, l = children.length; i < l; i ++) { | |
var child = fs.treeSync(path.join(root, children[i])) | |
child.name = children[i] | |
s.children.push(child) | |
} | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment