Created
November 15, 2022 11:47
-
-
Save arnoson/3237697e8c61dfaf0356f814b1500d7b to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively
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 { join } from 'node:path' | |
export const cleanupEmptyFolders = (folder) => { | |
if (!statSync(folder).isDirectory()) return | |
let files = readdirSync(folder) | |
if (files.length > 0) { | |
files.forEach((file) => cleanupEmptyFolders(join(folder, file))) | |
// 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
Very nice. In case anyone needs a version which excludes certain directories from the traversal (such as the ubiquitous
node_modules/
directory), here is a slight revision I made -- this should work for Typescript/Node:https://gist.github.com/rnag/a5e8dcea68979a5df4a946e41f75ea97
Measuring performance, I noted a huge improvement in my case. ~100 milliseconds down to ~1 millisecond. The reason is that otherwise it was traversing down a
node_modules
subfolder which had a ton of folders underneath it that it need to separately check.