Created
November 22, 2013 20:13
-
-
Save freidamachoi/7606071 to your computer and use it in GitHub Desktop.
another directory traversal method
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
var fs = require('fs'), | |
path = require('path'); | |
function dirTree(filename) { | |
var stats = fs.lstatSync(filename), | |
info = { | |
path: filename, | |
name: path.basename(filename) | |
}; | |
if (stats.isDirectory()) { | |
info.type = "folder"; | |
info.children = fs.readdirSync(filename).map(function(child) { | |
return dirTree(filename + '/' + child); | |
}); | |
} else { | |
// Assuming it's a file. In real life it could be a symlink or | |
// something else! | |
info.type = "file"; | |
} | |
return info; | |
} | |
if (module.parent === undefined) { | |
// node dirTree.js ~/foo/bar | |
var util = require('util'); | |
console.log(util.inspect(dirTree(process.argv[2]), false, null)); | |
} |
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' #file system module | |
path = require 'path' # file path module | |
# returns json tree of directory structure | |
tree = (root) -> | |
# clean trailing '/'(s) | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment