Skip to content

Instantly share code, notes, and snippets.

@rnag
Forked from arnoson/cleanupEmptyFolders.js
Last active February 3, 2023 22:20
Show Gist options
  • Save rnag/a5e8dcea68979a5df4a946e41f75ea97 to your computer and use it in GitHub Desktop.
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)
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