Last active
June 18, 2023 20:14
-
-
Save fixpunkt/fe32afe14fbab99d9feb4e8da7268445 to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively, async version of https://gist.github.com/jakub-g/5903dc7e4028133704a4
This file contains hidden or 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 fsPromises = require('fs').promises; | |
const path = require('path'); | |
/** | |
* Recursively removes empty directories from the given directory. | |
* | |
* If the directory itself is empty, it is also removed. | |
* | |
* Code taken from: https://gist.github.com/jakub-g/5903dc7e4028133704a4 | |
* | |
* @param {string} directory Path to the directory to clean up | |
*/ | |
async function removeEmptyDirectories(directory) { | |
// lstat does not follow symlinks (in contrast to stat) | |
const fileStats = await fsPromises.lstat(directory); | |
if (!fileStats.isDirectory()) { | |
return; | |
} | |
let fileNames = await fsPromises.readdir(directory); | |
if (fileNames.length > 0) { | |
const recursiveRemovalPromises = fileNames.map( | |
(fileName) => removeEmptyDirectories(path.join(directory, fileName)), | |
); | |
await Promise.all(recursiveRemovalPromises); | |
// re-evaluate fileNames; after deleting subdirectory | |
// we may have parent directory empty now | |
fileNames = await fsPromises.readdir(directory); | |
} | |
if (fileNames.length === 0) { | |
console.log('Removing: ', directory); | |
await fsPromises.rmdir(directory); | |
} | |
} | |
module.exports = { | |
removeEmptyDirectories, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!