Skip to content

Instantly share code, notes, and snippets.

@markjlorenz
Created October 12, 2012 18:53
Show Gist options
  • Save markjlorenz/3880822 to your computer and use it in GitHub Desktop.
Save markjlorenz/3880822 to your computer and use it in GitHub Desktop.
Uses Node.js's asynchronous file functions to recrusivly read a directory structure.
app.get "/ls", (req, res)->
path = "."
directoryCount = 0
edges = {} #key only for internal purpose {key:[], key2:[]}
nodes = {} #stores data for nodes
recursiveCalls = 0
nodeId = (path)->
"#{path}"
recursionComplete = ()->
console.log "-- Directory Count: ", directoryCount
res.send {rootId:nodeId(path), edges:edges, nodes:nodes}
getFiles = (path)->
recursiveCalls++
nodes[path] =
name: path
display: path.split('/').pop()
console.log "--", path
fs.readdir path, (err, files)->
directoryProps = (dir)->
recursiveCalls++
#uses lstat so symlinks are not followed means no cycles in graph
fs.lstat dir, (err, stats)->
if err
console.log "Error: ", err
recursiveCalls--
else if stats.isDirectory()
#add it to our tree
edgeKey = nodeId(path)
edges[edgeKey] or= [] #initialize if new
edges[edgeKey].push dir
directoryCount++
#recurse on it
getFiles dir
if --recursiveCalls == 0
recursionComplete()
recursiveCalls--
if files
directoryProps "#{path}/#{dir}" for dir in files
getFiles path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment