How to delete all files and subdirectories in a directory with Node.js

Viewed 2690

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!

2 Answers

You can use del package to delete files and folder within a directory recursively without deleting the parent directory:

  1. Install the required dependency:
    npm install del
    
  2. Use below code to delete subdirectories or files within Test directory without deleting Test directory itself:
    const del = require("del");
    
    del.sync(['Test/**', '!Test']);
    

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 :)

Related