Last active
December 15, 2015 06:39
-
-
Save skw/5217687 to your computer and use it in GitHub Desktop.
node.js coffeescript function that returns json tree representation of directory structure
This file contains hidden or 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
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