Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created November 13, 2016 12:21
Show Gist options
  • Select an option

  • Save nexpr/8b109a1d6caae265dadfde54f33fb00b to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/8b109a1d6caae265dadfde54f33fb00b to your computer and use it in GitHub Desktop.
nodejs get directory tree
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