Skip to content

Instantly share code, notes, and snippets.

@fixpunkt
Last active June 18, 2023 20:14
Show Gist options
  • Select an option

  • Save fixpunkt/fe32afe14fbab99d9feb4e8da7268445 to your computer and use it in GitHub Desktop.

Select an option

Save fixpunkt/fe32afe14fbab99d9feb4e8da7268445 to your computer and use it in GitHub Desktop.

Revisions

  1. fixpunkt revised this gist Jan 31, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion remove-empty-directories.js
    Original file line number Diff line number Diff line change
    @@ -11,7 +11,7 @@ const path = require('path');
    * @param {string} directory Path to the directory to clean up
    */
    async function removeEmptyDirectories(directory) {
    // lstatSync does not follow symlinks (in contrary to statSync)
    // lstat does not follow symlinks (in contrast to stat)
    const fileStats = await fsPromises.lstat(directory);
    if (!fileStats.isDirectory()) {
    return;
  2. fixpunkt created this gist Jan 31, 2020.
    39 changes: 39 additions & 0 deletions remove-empty-directories.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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) {
    // lstatSync does not follow symlinks (in contrary to statSync)
    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,
    };