Created
August 27, 2010 03:24
-
-
Save isaacs/552721 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
module.exports = tree | |
tree.sync = treeSync | |
var fs = require("fs") | |
, path = require("path") | |
function tree (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 = null | |
children.forEach(function (child) { | |
var i = index ++ | |
if (error) return | |
tree(path.join(root, child), function (er, t) { | |
if (error) return | |
if (er) return cb(error = er) | |
t.name = child | |
t.path = path.join(root, child) | |
s.children[i] = t | |
if (--childrenWaiting === 0) cb(null, s) | |
}) | |
}) | |
}) | |
}) | |
} | |
function treeSync (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 = treeSync(path.join(root, children[i])) | |
child.name = children[i] | |
child.path = path.join(root, children[i]) | |
s.children.push(child) | |
} | |
return s | |
} | |
if (module !== process.mainModule) return | |
tree("/Users", function (er, ok) { | |
console.error((er && er.stack) || ok) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment