Remove directory which is not empty
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?
As of 2019...
As of Node.js 12.10.0, fs.rmdirSync
supports a recursive
options, so you can finally do:
fs.rmdirSync(dir, { recursive: true });
Where the recursive
option deletes the entire directory recursively.
Update: The recursive
option in fs.rmdir
/ fs.rmdirSync
has been deprecated however, so use fs.rm
/ fs.rmSync
instead:
fs.rmSync(dir, { recursive: true, force: true });
The force: true
option ignores exceptions if dir
does not exist. More info see the fs.rmSync
docs
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");
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);
}
};
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);
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');