Skip to content

Instantly share code, notes, and snippets.

@isaacs
Created April 23, 2010 22:19
Show Gist options
  • Save isaacs/377246 to your computer and use it in GitHub Desktop.
Save isaacs/377246 to your computer and use it in GitHub Desktop.
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