Remove a Directory's Files & Sub-Directories in NodeJS
Are you working with system files in Node.js and need a way to remove all of the contents in a directory? Including files that may be inside additional sub-directories?
In this article, we'll show you how to do just that.
For the code in this article to work, make sure you have Node.js installed and a directory to work with.
Below we have written a function that recursively moves through a directory and all it's sub-directories and removes every file it finds.
We'll give you the full code and explain everything afterward.
Full code:
Node.js
 
const fs = require("fs")
const path = require("path")
 
const removeDir = function(path) {
  if (fs.existsSync(path)) {
    const files = fs.readdirSync(path)
 
    if (files.length > 0) {
      files.forEach(function(filename) {
        if (fs.statSync(path + "/" + filename).isDirectory()) {
          removeDir(path + "/" + filename)
        } else {
          fs.unlinkSync(path + "/" + filename)
        }
      })
    } else {
      console.log("No files found in the directory.")
    }
  } else {
    console.log("Directory path not found.")
  }
}
 
const pathToDir = path.join(__dirname, "your-directory")
 
removeDir(pathToDir)
There's a lot going on here, so let's break down each section.
The removeDir function is what we use to recursively remove a parent directory and it's files and sub-directories. The only parameter is the path to the parent directory.
Inside the removeDir function, the first thing we do is use the fs.existsSync() to verify that the directory we passed to our function exists. If it doesn't exist, we end the function and log an error message.
Then, we pass our directory path to the fs.readdirSync() function to get an array of all the files and sub-directories inside the parent directory. And we store that array in a variable named files.
If the array is empty, we log an error message and end the function.
If the array.length > 0, we loop through the files array with the forEach() function. For each item in the files array, we check whether or not the item is a file or a sub-directory.
If the item is a sub-directory, we have the function recursively call itself with removeDir(), with the path of the sub-directory as a parameter. That function will loop through the sub-directory and remove it's children files and directories.
And if the item is a file, we simply use the fs.unlinkSync() to remove the file, with the path to the file given as a parameter.
Then we call our removeDir(pathToDir) function with the path to the parent directory as a parameter.
When you run the code, you should see that the directory in question is removed.