Skip to content

Instantly share code, notes, and snippets.

@g45t345rt
Created June 27, 2020 18:05
Show Gist options
  • Save g45t345rt/22a356fdba70a04932db2c37a0f9691a to your computer and use it in GitHub Desktop.
Save g45t345rt/22a356fdba70a04932db2c37a0f9691a to your computer and use it in GitHub Desktop.
Remove empty folders from directory-tree
const dirTree = require('directory-tree')
const removeEmptyFolder = (obj, parent) => {
const { children, name } = obj
if (children) {
let i = children.length
while (i--) {
const child = children[i]
removeEmptyFolder(child, obj)
}
if (children.length === 0) {
const index = parent.children.findIndex((child) => child.name === name)
parent.children.splice(index, 1)
}
}
}
const data = dirTree('{your_folder_path}')
removeEmptyFolder(data)
@ThatIsAPseudo
Copy link

Thanks for this snippet !
Line 12 should be if (children.length === 0 && parent) to handle the (corner) case where the first path given to the function is itself an empty folder. Otherwise it'll throw a TypeError: Cannot read property 'children' of undefined error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment