Remove directory which is not empty

node.jsFilesystems

node.js Problem Overview


In my Node application I need to remove a directory which has some files, but fs.rmdir only works on empty directories. How can I do this?

node.js Solutions


Solution 1 - node.js

As of Node.js 14.14.0, the recommended way is to use fs.rmSync:

fs.rmSync(dir, { recursive: true, force: true });

Solution 2 - node.js

There is a module for this called rimraf (https://npmjs.org/package/rimraf). It provides the same functionality as rm -Rf

Async usage:

var rimraf = require("rimraf");
rimraf("/some/directory", function () { console.log("done"); });

Sync usage:

rimraf.sync("/some/directory");

Solution 3 - node.js

To remove folder synchronously

    const fs = require('fs');
    const Path = require('path');

    const deleteFolderRecursive = function (directoryPath) {
    if (fs.existsSync(directoryPath)) {
        fs.readdirSync(directoryPath).forEach((file, index) => {
          const curPath = path.join(directoryPath, file);
          if (fs.lstatSync(curPath).isDirectory()) {
           // recurse
            deleteFolderRecursive(curPath);
          } else {
            // delete file
            fs.unlinkSync(curPath);
          }
        });
        fs.rmdirSync(directoryPath);
      }
    };

Solution 4 - node.js

Most of the people using fs with Node.js would like functions close to the "Unix way" of dealing with files. I'm using fs-extra to bring all the cool stuff :

> fs-extra contains methods that aren't included in the vanilla Node.js > fs package. Such as mkdir -p, cp -r, and rm -rf.

Even better, fs-extra is a drop in replacement for native fs. All methods in fs are unmodified and attached to it. It means that you can replace fs by fs-extra :

// this can be replaced
const fs = require('fs')

// by this
const fs = require('fs-extra')

And then you can remove a folder this way:

fs.removeSync('/tmp/myFolder'); 
//or
fs.remove('/tmp/myFolder', callback);

Solution 5 - node.js

As of Node v14 (October 2020), the fs module has fs.rm and rs.rmSync that support recursive, non-empty directory unlinking:

https://nodejs.org/docs/latest-v14.x/api/fs.html#fs_fs_rm_path_options_callback

So you can now do something like this:

const fs = require('fs');
fs.rm('/path/to/delete', { recursive: true }, () => console.log('done'));

or:

const fs = require('fs');
fs.rmSync('/path/to/delete', { recursive: true });
console.log('done');

Solution 6 - node.js

My modified answer from @oconnecp (https://stackoverflow.com/a/25069828/3027390)

Uses path.join for better cross-platform experience. So, don't forget to require it.

var path = require('path');

Also renamed function to rimraf ;)

/**
 * Remove directory recursively
 * @param {string} dir_path
 * @see https://stackoverflow.com/a/42505874/3027390
 */
function rimraf(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function(entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                rimraf(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

Solution 7 - node.js

I don't usually resurrect old threads but there is a lot on churn here and sans the rimraf answer these all seem overly complicated to me.

First in modern Node (>= v8.0.0) you can simplify the process using only node core modules, fully asynchronous, and parallelize the unlinking of files concurrently all in a function of five lines and still keep readability:

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const rmdir = promisify(fs.rmdir);
const unlink = promisify(fs.unlink);

exports.rmdirs = async function rmdirs(dir) {
  let entries = await readdir(dir, { withFileTypes: true });
  await Promise.all(entries.map(entry => {
    let fullPath = path.join(dir, entry.name);
    return entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
  }));
  await rmdir(dir);
};

On another note a guard for path traversal attacks is inappropriate for this function because

  1. It is out of scope based on the Single Responsibility Principle.
  2. Should be handled by the caller not this function. This is akin to the command-line rm -rf in that it takes an argument and will allow the user to rm -rf / if asked to. It would be the responsibility of a script to guard not the rm program itself.
  3. This function would be unable to determine such an attack since it does not have a frame of reference. Again that is the responsibility of the caller who would have the context of intent which would provide it a reference to compare the path traversal.
  4. Sym-links are not a concern as .isDirectory() is false for sym-links and are unlinked not recursed into.

Last but not least, there is a rare race condition that the recursion could error if one of the entries was unlinked or deleted outside this script at just the right time while this recursion is running. Since this scenario is not typical in most environments it can likely be overlooked. However, if required (for some edge cases) this issue can be mitigated with this slightly more complex example:

exports.rmdirs = async function rmdirs(dir) {
  let entries = await readdir(dir, { withFileTypes: true });
  let results = await Promise.all(entries.map(entry => {
    let fullPath = path.join(dir, entry.name);
    let task = entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
    return task.catch(error => ({ error }));
  }));
  results.forEach(result => {
    // Ignore missing files/directories; bail on other errors
    if (result && result.error.code !== 'ENOENT') throw result.error;
  });
  await rmdir(dir);
};

EDIT: Make isDirectory() a function. Remove the actual directory at the end. Fix missing recursion.

Solution 8 - node.js

Here is an async version of @SharpCoder's answer

const fs = require('fs');
const path = require('path');

function deleteFile(dir, file) {
	return new Promise(function (resolve, reject) {
		var filePath = path.join(dir, file);
		fs.lstat(filePath, function (err, stats) {
			if (err) {
				return reject(err);
			}
			if (stats.isDirectory()) {
				resolve(deleteDirectory(filePath));
			} else {
				fs.unlink(filePath, function (err) {
					if (err) {
						return reject(err);
					}
					resolve();
				});
			}
		});
	});
};

function deleteDirectory(dir) {
	return new Promise(function (resolve, reject) {
		fs.access(dir, function (err) {
			if (err) {
				return reject(err);
			}
			fs.readdir(dir, function (err, files) {
				if (err) {
					return reject(err);
				}
				Promise.all(files.map(function (file) {
					return deleteFile(dir, file);
				})).then(function () {
					fs.rmdir(dir, function (err) {
						if (err) {
							return reject(err);
						}
						resolve();
					});
				}).catch(reject);
			});
		});
	});
};

Solution 9 - node.js

I wrote this function called remove folder. It will recursively remove all the files and folders in a location. The only package it requires is async.

var async = require('async');

function removeFolder(location, next) {
    fs.readdir(location, function (err, files) {
        async.each(files, function (file, cb) {
            file = location + '/' + file
            fs.stat(file, function (err, stat) {
                if (err) {
                    return cb(err);
                }
                if (stat.isDirectory()) {
                    removeFolder(file, cb);
                } else {
                    fs.unlink(file, function (err) {
                        if (err) {
                            return cb(err);
                        }
                        return cb();
                    })
                }
            })
        }, function (err) {
            if (err) return next(err)
            fs.rmdir(location, function (err) {
                return next(err)
            })
        })
    })
}

Solution 10 - node.js

[EDIT: using node.js v15.5.0]

Having just tried using some of the solutions posted here, I encountered the following deprecation warning:

> (node:13202) [DEP0147] DeprecationWarning: In future versions of > Node.js, fs.rmdir(path, { recursive: true }) will throw if path does > not exist or is a file. Use fs.rm(path, { recursive: true, force: true > }) instead

fs.rm(path, { recursive: true, force: true }); works nicely, with fs.rmSync(path, { recursive: true, force: true }); if you want to use the blocking version.

Solution 11 - node.js

If you are using node 8+ want asyncronicity and don't want external dependencies, here is the async/await version:

const path = require('path');
const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const lstat = util.promisify(fs.lstat);
const unlink = util.promisify(fs.unlink);
const rmdir = util.promisify(fs.rmdir);

const removeDir = async (dir) => {
    try {
        const files = await readdir(dir);
        await Promise.all(files.map(async (file) => {
            try {
                const p = path.join(dir, file);
                const stat = await lstat(p);
                if (stat.isDirectory()) {
                    await removeDir(p);
                } else {
                    await unlink(p);
                    console.log(`Removed file ${p}`);
                }
            } catch (err) {
                console.error(err);
            }
        }))
        await rmdir(dir);
        console.log(`Removed dir ${dir}`);
    } catch (err) {
      console.error(err);
    }
}

Solution 12 - node.js

const fs = require("fs");
fs.rmdir("./test", { recursive: true }, (err) => {
  if (err) {
    console.error(err);
  }
});

Provide the recursive: true option. And it will recursively delete all the files and directories of the given path. (Assuming test is directory present at root. )

Solution 13 - node.js

I reached here while trying to get over with the gulp and I'm writing for further reaches.

When you want to delete files and folders using del, you should append /** for recursive deletion.

gulp.task('clean', function () {
    return del(['some/path/to/delete/**']);
});

Solution 14 - node.js

Async version of @SharpCoder's answer using fs.promises:

const fs = require('fs');
const afs = fs.promises;

const deleteFolderRecursive = async path =>  {
    if (fs.existsSync(path)) {
        for (let entry of await afs.readdir(path)) {
            const curPath = path + "/" + entry;
            if ((await afs.lstat(curPath)).isDirectory())
                await deleteFolderRecursive(curPath);
            else await afs.unlink(curPath);
        }
        await afs.rmdir(path);
    }
};

Solution 15 - node.js

In the latest version of Node.js (12.10.0 or later), the rmdir style functions fs.rmdir(), fs.rmdirSync(), and fs.promises.rmdir() have a new experimental option recursive that allows deleting non-empty directories, e.g.

fs.rmdir(path, { recursive: true });

The related PR on GitHub: https://github.com/nodejs/node/pull/29168

Solution 16 - node.js

According to the fs documentation, fsPromises currently provides the recursive option on an experimental basis, which, at least in my own case on Windows, removes the directory and any files therein.

fsPromises.rmdir(path, {
  recursive: true
})

Does recursive: true remove the files on Linux and MacOS?

Solution 17 - node.js

Explanations

As of Node.js v14, we can now use the require("fs").promises.rm function to remove a file using a promise. The first argument will be the file or folder to remove (even non-existant ones). You can use the recursive and force options in the second argument's object to mimic the behavior of the rm Shell command utility with the -rf options.

Example

"use strict";

require("fs").promises.rm("directory", {recursive: true, force: true}).then(() => {
  console.log("removed");
}).catch(error => {
  console.error(error.message);
});

See

Node.js v14 Documentation

Mozilla Developer Promises Documentation

rm command manual page

Solution 18 - node.js

as written here.

>To get a behavior similar to the rm -rf Unix command, use fs.rm() with options { recursive: true, force: true }.

Solution 19 - node.js

2020 Update

From version 12.10.0 recursiveOption has been added for options.

Note that recursive deletion is experimental.

So you would do for sync:

fs.rmdirSync(dir, {recursive: true});

or for async:

fs.rmdir(dir, {recursive: true});

Solution 20 - node.js

return new Promise((resolve, reject) => {
  const fs = require("fs");
  // directory path
  const dir = "your/dir";

  // delete directory recursively <------
  fs.rmdir(dir, { recursive: true }, (err) => {
    if (err) {
      reject(err);
    }
    resolve(`${dir} is deleted!`);
  });
});

Solution 21 - node.js

Just use rmdir module! it's easy and simple.

Solution 22 - node.js

The de facto package is rimraf, but here is my tiny async version:

const fs = require('fs')
const path = require('path')
const Q = require('q')

function rmdir (dir) {
  return Q.nfcall(fs.access, dir, fs.constants.W_OK)
    .then(() => {
      return Q.nfcall(fs.readdir, dir)
        .then(files => files.reduce((pre, f) => pre.then(() => {
          var sub = path.join(dir, f)
          return Q.nfcall(fs.lstat, sub).then(stat => {
            if (stat.isDirectory()) return rmdir(sub)
            return Q.nfcall(fs.unlink, sub)
          })
        }), Q()))
    })
    .then(() => Q.nfcall(fs.rmdir, dir))
}

Solution 23 - node.js

A quick and dirty way (maybe for testing) could be to directly use the exec or spawn method to invoke OS call to remove the directory. Read more on NodeJs child_process.

let exec = require('child_process').exec
exec('rm -Rf /tmp/*.zip', callback)

Downsides are:

  1. You are depending on underlying OS i.e. the same method would run in unix/linux but probably not in windows.
  2. You cannot hijack the process on conditions or errors. You just give the task to underlying OS and wait for the exit code to be returned.

Benefits:

  1. These processes can run asynchronously.
  2. You can listen for the output/error of the command, hence command output is not lost. If operation is not completed, you can check the error code and retry.

Solution 24 - node.js

Ultra-speed and fail-proof

You can use the lignator package (https://www.npmjs.com/package/lignator), it's faster than any async code (e.g. rimraf) and more fail-proof (especially in Windows, where file removal is not instantaneous and files might be locked by other processes).

> 4,36 GB of data, 28 042 files, 4 217 folders on Windows removed in 15 seconds vs rimraf's 60 seconds on old HDD.

const lignator = require('lignator');

lignator.remove('./build/');

Solution 25 - node.js

Sync folder remove with the files or only a file.

I am not much of a giver nor a contributor but I couldn't find a good solution of this problem and I had to find my way... so I hope you'll like it :)

Works perfect for me with any number of nested directories and sub directories. Caution for the scope of 'this' when recursing the function, your implementation may be different. In my case this function stays into the return of another function that's why I am calling it with this.

    const fs = require('fs');

    deleteFileOrDir(path, pathTemp = false){
            if (fs.existsSync(path)) {
                if (fs.lstatSync(path).isDirectory()) {
                    var files = fs.readdirSync(path);
                    if (!files.length) return fs.rmdirSync(path);
                    for (var file in files) {
                        var currentPath = path + "/" + files[file];
                        if (!fs.existsSync(currentPath)) continue;
                        if (fs.lstatSync(currentPath).isFile()) {
                            fs.unlinkSync(currentPath);
                            continue;
                        }
                        if (fs.lstatSync(currentPath).isDirectory() && !fs.readdirSync(currentPath).length) {
                            fs.rmdirSync(currentPath);
                        } else {
                            this.deleteFileOrDir(currentPath, path);
                        }
                    }
                    this.deleteFileOrDir(path);
                } else {
                    fs.unlinkSync(path);
                }
            }
            if (pathTemp) this.deleteFileOrDir(pathTemp);
        }

Solution 26 - node.js

2020 Answer

If you want to do it in a npm script, You DON'T need to previously install any 3rd party package if you use the command npx

If for example, you want to delete the folders dist and .cache when you run npm run clean then just add this command to your package.json

{
  "scripts": {
    "clean": "npx rimraf dist .cache"
  }
}

It will work in any operative system

Solution 27 - node.js

I wish there was a way to do this without additional modules for something so minuscule and common, but this is the best I could come up with.

Update: Should now work on Windows (tested Windows 10), and should also work on Linux/Unix/BSD/Mac systems.

const
    execSync = require("child_process").execSync,
    fs = require("fs"),
    os = require("os");

let removeDirCmd, theDir;

removeDirCmd = os.platform() === 'win32' ? "rmdir /s /q " : "rm -rf ";

theDir = __dirname + "/../web-ui/css/";

// WARNING: Do not specify a single file as the windows rmdir command will error.
if (fs.existsSync(theDir)) {
    console.log(' removing the ' + theDir + ' directory.');
    execSync(removeDirCmd + '"' + theDir + '"', function (err) {
        console.log(err);
    });
}

Solution 28 - node.js

Another alternative is using the fs-promise module that provides promisified versions of the fs-extra modules

you could then write like this example:

const { remove, mkdirp, writeFile, readFile } = require('fs-promise')
const { join, dirname } = require('path')

async function createAndRemove() {
  const content = 'Hello World!'
  const root = join(__dirname, 'foo')
  const file = join(root, 'bar', 'baz', 'hello.txt')

  await mkdirp(dirname(file))
  await writeFile(file, content)
  console.log(await readFile(file, 'utf-8'))
  await remove(join(__dirname, 'foo'))
}

createAndRemove().catch(console.error)

note: async/await requires a recent nodejs version (7.6+)

Solution 29 - node.js

const fs = require("fs")
const path = require("path")

let _dirloc = '<path_do_the_directory>'

if (fs.existsSync(_dirloc)) {
  fs.readdir(path, (err, files) => {
    if (!err) {
      for (let file of files) {
        // Delete each file
        fs.unlinkSync(path.join(_dirloc, file))
      }
    }
  })
  // After the 'done' of each file delete,
  // Delete the directory itself.
  if (fs.unlinkSync(_dirloc)) {
    console.log('Directory has been deleted!')
  }
}

Solution 30 - node.js

This is one approach using promisify and two help functions (to and toAll) to resolve the promise.

It does all actions asynchrounous.

const fs = require('fs');
const { promisify } = require('util');
const to = require('./to');
const toAll = require('./toAll');

const readDirAsync = promisify(fs.readdir);
const rmDirAsync = promisify(fs.rmdir);
const unlinkAsync = promisify(fs.unlink);

/**
    * @author Aécio Levy
    * @function removeDirWithFiles
    * @usage: remove dir with files
    * @param {String} path
    */
const removeDirWithFiles = async path => {
    try {
        const file = readDirAsync(path);
        const [error, files] = await to(file);
        if (error) {
            throw new Error(error)
        }
        const arrayUnlink = files.map((fileName) => {
            return unlinkAsync(`${path}/${fileName}`);
        });
        const [errorUnlink, filesUnlink] = await toAll(arrayUnlink);
        if (errorUnlink) {
            throw new Error(errorUnlink);
        }
        const deleteDir = rmDirAsync(path);
        const [errorDelete, result] = await to(deleteDir);
        if (errorDelete) {
            throw new Error(errorDelete);
        }
    } catch (err) {
        console.log(err)
    }
}; 

Solution 31 - node.js

//without use of any third party lib

const fs = require('fs');
var FOLDER_PATH = "./dirname";
var files = fs.readdirSync(FOLDER_PATH);
files.forEach(element => {
    fs.unlinkSync(FOLDER_PATH + "/" + element);
});
fs.rmdirSync(FOLDER_PATH);

Solution 32 - node.js

While recursive is an experimental option of fs.rmdir

function rm (path, cb) {
	fs.stat(path, function (err, stats) {
        if (err)
            return cb(err);

		if (stats.isFile())
			return fs.unlink(path, cb);

		fs.rmdir(path, function (err) {
			if (!err || err && err.code != 'ENOTEMPTY') 
				return cb(err);

			fs.readdir(path, function (err, files) {
				if (err)
					return cb(err);

				let next = i => i == files.length ? 
					rm(path, cb) : 
					rm(path + '/' + files[i], err => err ? cb(err) : next(i + 1));

				next(0);
			});
		});
	});
}

Solution 33 - node.js

❄️ You can use graph-fs
directory.delete()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsachinView Question on Stackoverflow
Solution 1 - node.jsuser6269864View Answer on Stackoverflow
Solution 2 - node.jsMorgan ARR AllenView Answer on Stackoverflow
Solution 3 - node.jsSharpCoderView Answer on Stackoverflow
Solution 4 - node.jsPierre MaouiView Answer on Stackoverflow
Solution 5 - node.jsElliot PlantView Answer on Stackoverflow
Solution 6 - node.jsthybziView Answer on Stackoverflow
Solution 7 - node.jsSukimaView Answer on Stackoverflow
Solution 8 - node.jsTony BrixView Answer on Stackoverflow
Solution 9 - node.jsoconnecpView Answer on Stackoverflow
Solution 10 - node.jstherightstuffView Answer on Stackoverflow
Solution 11 - node.jsRonZView Answer on Stackoverflow
Solution 12 - node.jsFaiziView Answer on Stackoverflow
Solution 13 - node.jsJin KwonView Answer on Stackoverflow
Solution 14 - node.jsError404View Answer on Stackoverflow
Solution 15 - node.jsGOTO 0View Answer on Stackoverflow
Solution 16 - node.jsoldboyView Answer on Stackoverflow
Solution 17 - node.jsAmin NAIRIView Answer on Stackoverflow
Solution 18 - node.jsmdmundoView Answer on Stackoverflow
Solution 19 - node.jsGiovanni PatrunoView Answer on Stackoverflow
Solution 20 - node.jsphreakphreakView Answer on Stackoverflow
Solution 21 - node.jsAminovskiView Answer on Stackoverflow
Solution 22 - node.jsclarkttfuView Answer on Stackoverflow
Solution 23 - node.jsRashView Answer on Stackoverflow
Solution 24 - node.jsHankMoodyView Answer on Stackoverflow
Solution 25 - node.jsMetaTronView Answer on Stackoverflow
Solution 26 - node.jsJuanma MenendezView Answer on Stackoverflow
Solution 27 - node.jsb01View Answer on Stackoverflow
Solution 28 - node.jsMax FichtelmannView Answer on Stackoverflow
Solution 29 - node.jsErisan OlasheniView Answer on Stackoverflow
Solution 30 - node.jsAecio LevyView Answer on Stackoverflow
Solution 31 - node.jsAmyView Answer on Stackoverflow
Solution 32 - node.jsAikon MogwaiView Answer on Stackoverflow
Solution 33 - node.jsYairoproView Answer on Stackoverflow