Created
October 12, 2012 18:53
-
-
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.
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
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