Reputation: 289
I am working with node.js and need to empty a folder. I read a lot of deleting files or folders. But I didn't find answers, how to delete all files AND folders in my folder Test
, without deleting my folder Test` itself.
I try to find a solution with fs
or extra-fs
. Happy for some help!
Upvotes: 5
Views: 13391
Reputation: 61
const fs = require("fs");
// Node fs module "rmdirSync" is deprecated since v16.0.0.
fs.rmdirSync('./del_path', {recursive: true,});
// Node fs module "rmSync" support is starting from v14.14.0.
fs.rmSync('./del_path', {recursive: true, force: true,});
// If you do not want to care about the node version,
// just use unix command "rm -rf" instead by installing "shelljs" package.
const shell = require("shelljs");
shell.rm('-rf', './del_path');
Upvotes: 0
Reputation: 5644
You can use del package to delete files and folder within a directory recursively without deleting the parent directory:
npm install del
Test
directory without deleting Test
directory itself:
const del = require("del");
del.sync(['Test/**', '!Test']);
Upvotes: 1
Reputation: 1595
EDIT 1: Hey @Harald, you should use the del library that @ziishaned posted above. Because it's much more clean and scalable. And use my answer to learn how it works under the hood :)
EDIT: 2 (Dec 26 2021): I didn't know that there is a fs
method named fs.rm
that you can use to accomplish the task with just one line of code.
fs.rm(path_to_delete, { recursive: true }, callback)
// or use the synchronous version
fs.rmSync(path_to_delete, { recursive: true })
The above code is analogous to the linux shell command: rm -r path_to_delete
.
We use fs.unlink
and fs.rmdir
to remove files and empty directories respectively. To check if a path represents a directory we can use fs.stat()
.
So we've to list all the contents in your test
directory and remove them one by one.
By the way, I'll be using the synchronous version of fs
methods mentioned above (e.g., fs.readdirSync
instead of fs.readdir
) to make my code simple. But if you're writing a production application then you should use asynchronous version of all the fs methods. I leave it up to you to read the docs here Node.js v14.18.1 File System documentation.
const fs = require("fs");
const path = require("path");
const DIR_TO_CLEAR = "./trash";
emptyDir(DIR_TO_CLEAR);
function emptyDir(dirPath) {
const dirContents = fs.readdirSync(dirPath); // List dir content
for (const fileOrDirPath of dirContents) {
try {
// Get Full path
const fullPath = path.join(dirPath, fileOrDirPath);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
// It's a sub directory
if (fs.readdirSync(fullPath).length) emptyDir(fullPath);
// If the dir is not empty then remove it's contents too(recursively)
fs.rmdirSync(fullPath);
} else fs.unlinkSync(fullPath); // It's a file
} catch (ex) {
console.error(ex.message);
}
}
}
Feel free to ask me if you don't understand anything in the code above :)
Upvotes: 7