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!
CodePudding user response:
You can use del package to delete files and folder within a directory recursively without deleting the parent directory:
- Install the required dependency:
npm install del
- Use below code to delete subdirectories or files within
Test
directory without deletingTest
directory itself:const del = require("del"); del.sync(['Test/**']);
CodePudding user response:
EDIT : 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 :)
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 :)