Created
November 13, 2016 12:21
-
-
Save nexpr/8b109a1d6caae265dadfde54f33fb00b to your computer and use it in GitHub Desktop.
nodejs get directory tree
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
| function getDirectoryTree(start_dirpath, {dir = true, file = true, max_depth = -1, flatten = false} = {}){ | |
| const tree = {} | |
| dir = !!dir | |
| file = !!file | |
| max_depth = ~~max_depth | |
| flatten = !!flatten | |
| !function recur(dirpath, store, depth){ | |
| if(depth > max_depth && max_depth >= 0) return | |
| for(const name of fs.readdirSync(dirpath)){ | |
| const realpath = fs.realpathSync(dirpath + "/" + name); | |
| if(fs.statSync(realpath).isDirectory()){ | |
| if(!dir) continue | |
| const subtree = {"": realpath} | |
| store[name] = subtree | |
| recur(realpath, subtree, depth + 1) | |
| }else{ | |
| if(!file) continue | |
| store[name] = realpath | |
| } | |
| } | |
| }(start_dirpath, tree, 1) | |
| if(flatten){ | |
| const paths = [] | |
| !function seek(node){ | |
| Object.values(node).forEach(e => { | |
| if(typeof e === "object"){ | |
| seek(e) | |
| }else{ | |
| paths.push(e) | |
| } | |
| }) | |
| }(tree) | |
| return paths | |
| } | |
| return tree | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment