Created
June 27, 2020 18:05
-
-
Save g45t345rt/22a356fdba70a04932db2c37a0f9691a to your computer and use it in GitHub Desktop.
Remove empty folders from directory-tree
This file contains 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aTypeError: Cannot read property 'children' of undefined
error.