-
-
Save rnag/a5e8dcea68979a5df4a946e41f75ea97 to your computer and use it in GitHub Desktop.
ts/node: remove empty directories recursively. `exclude` is a list of directories to not traverse (optimization)
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
import { readdirSync, rmdirSync, statSync } from 'node:fs'; | |
import { basename, join } from 'node:path'; | |
export const cleanupEmptyFolders = ( | |
folder: string, | |
exclude: string[] = ['node_modules'] | |
) => { | |
if (!statSync(folder).isDirectory()) return; | |
const folderName = basename(folder); | |
if (exclude && exclude.includes(folderName)) { | |
console.log(`skipping: ${folderName}`); | |
return; | |
} | |
let files = readdirSync(folder); | |
if (files.length > 0) { | |
files.forEach((file) => | |
cleanupEmptyFolders(join(folder, file), exclude) | |
); | |
// Re-evaluate files; after deleting subfolders we may have an empty parent | |
// folder now. | |
files = readdirSync(folder); | |
} | |
if (files.length == 0) { | |
console.log(`removing: ${folder}`); | |
rmdirSync(folder); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment