Skip to content

Instantly share code, notes, and snippets.

@rodw
Created October 10, 2013 02:52
Show Gist options
  • Save rodw/6912281 to your computer and use it in GitHub Desktop.
Save rodw/6912281 to your computer and use it in GitHub Desktop.
Here's a little CoffeeScript routine that will recursively read the file-system, generating an object that represents a complete directory tree. This gist should be executable. You can run it with: `coffee directory-reader.coffee [FILENAME]` to dump a JSON representation of the object to stdout.
# Here's a little CoffeeScript routine that will recursively
# read the file-system, generating an object that represents
# a directory tree.
# The returned object will contain the following attributes:
#
# * `file` - the basename of the file.
# * `dir` - the directory containing the file.
# * `types` - an array containing zero or more of
# "File", "Directory", "SymbolicLink", "BlockDevice",
# "CharacterDevice", "FIFO" or "Socket".
# * `children` - when the "file" is a directory, this will be an
# array of nodes like this one, representing
# the items within the directory.
path = require 'path'
fs = require 'fs'
read_directory_tree = (parentdir,file)=>
make_node = (parentdir,file)=>
if parentdir? and (not file?)
file = parentdir
parentdir = null
node = {}
unless /^(\/|~)/.test file
parentdir ?= process.cwd()
node.dir = parentdir
node.fullpath = path.join(parentdir,file)
else
node.fullpath = file
node.file = file
stats = fs.lstatSync(node.fullpath)
node.types = []
if stats.isSymbolicLink()
node.types.push 'SymbolicLink'
stats = fs.statSync(node.fullpath)
for type in [ 'File', 'Directory', 'BlockDevice', 'CharacterDevice', 'FIFO', 'Socket' ]
if stats["is#{type}"]?()
node.types.push type
return node
visit = (node)=>
if 'Directory' in node.types
node.children = []
files = fs.readdirSync(node.fullpath)
for file in files
child = make_node(node.fullpath,file)
node.children.push child
visit(child)
child.stats
return node
return visit(make_node(parentdir,file))
# For example: (run with `coffee directory-reader.coffee [FILENAME]`)
if require.main is module
root = process.argv[2]
tree = read_directory_tree(root)
console.log JSON.stringify(tree,null,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment