Skip to content

Instantly share code, notes, and snippets.

@skw
Last active December 15, 2015 06:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skw/5217687 to your computer and use it in GitHub Desktop.
Save skw/5217687 to your computer and use it in GitHub Desktop.
node.js coffeescript function that returns json tree representation of directory structure
fs = require 'fs' # node file system module
path = require 'path' # node path module
# returns json tree representation of directory structure
tree = (root) ->
# clean trailing '/'
root = root.replace /\/+$/ , ""
# extract tree ring if root exists
if fs.existsSync root
ring = fs.lstatSync root
else
return 'error: root does not exist'
# type agnostic info
info =
path: root
name: path.basename(root)
# dir
if ring.isDirectory()
info.type = 'folder'
# execute for each child and call tree recursively
info.children = fs.readdirSync(root) .map (child) ->
tree root + '/' + child
# file
else if ring.isFile()
info.type = 'file'
# link
else if ring.isSymbolicLink()
info.type = 'link'
# other
else
info.type = 'unknown'
# return tree
info
# error handling
handle = (e) ->
return 'error: uncaught exception...'
exports.index = (req, res) ->
try
res.send tree './test/'
catch e
res.send handle e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment