-
-
Save davidwalter0/b4b0bd0709046d81543734df908c1d36 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.
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
# 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