Skip to content

Instantly share code, notes, and snippets.

@arnoson
Created November 15, 2022 11:47
Show Gist options
  • Save arnoson/3237697e8c61dfaf0356f814b1500d7b to your computer and use it in GitHub Desktop.
Save arnoson/3237697e8c61dfaf0356f814b1500d7b to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively
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)
}
}
@rnag
Copy link

rnag commented Feb 3, 2023

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.

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