Skip to content

Instantly share code, notes, and snippets.

@jots
Created June 22, 2011 19:43
Show Gist options
  • Save jots/1040965 to your computer and use it in GitHub Desktop.
Save jots/1040965 to your computer and use it in GitHub Desktop.
create directory structure
def dt(path,name=nil)
if not name
data = {}
data[:root] = children = []
else
data = {:name => name }
data[:branches] = children = []
end
dirs = []; files = []
Dir.foreach(path) do |entry|
next if (entry == '..' || entry == '.')
if File.directory?(File.join(path, entry))
dirs << entry
else
files << entry
end
end
dirs.sort.each do |d|
full_path = File.join(path, d)
children << dt(full_path, d)
end
files.sort.each do |f|
children << {:name => f}
end
return data
end
#!/usr/bin/env coffee
# looking to generate something like:
# {"root":[{"name":"a","branches":[{"name":"aa"},{"name":"bb"}]},{"name":"b"},{"name":"c"}]}
fs = require 'fs'
Path = require 'path'
dir_tree = (path,name=null) ->
if not name
data = {}
data["root"] = children = []
else
data = {"name": name }
data["branches"] = children = []
dirs = []; files = []
fs.readdir path,(err,files) =>
for entry in files
continue if entry == '..' || entry == '.'
fs.stat entry,(err,stat) =>
#### XXX Entry is set to the first element
console.log entry
if stat.isDirectory()
dirs.push(entry)
else
files.push(entry)
for d in dirs # XXX need to sort
children.push(dir_tree(Path.join(path,d),d))
for f in files # XXX need to sort
children.push {"name": f }
return data
## XX returns empty: { root: [] }
console.log dir_tree(".")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment