Thanks to visit codestin.com
Credit goes to coreui.io

How to delete directories in Node.js

Deleting directories programmatically is essential for cleanup operations, temporary file management, and maintaining organized file systems in Node.js applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented directory cleanup in numerous build processes and file management utilities over 25 years of development. From my expertise, the most reliable approach is using fs.rm() with the recursive option, which can handle both empty and non-empty directories safely. This provides comprehensive directory removal capabilities for modern Node.js applications.

Use fs.rm() with recursive option to delete directories and their contents.

const fs = require('fs')

fs.rm('./temp-folder', { recursive: true, force: true }, (err) => {
  if (err) throw err
  console.log('Directory deleted successfully')
})

Here fs.rm() removes the directory and all its contents recursively. The { recursive: true } option allows deletion of non-empty directories, while { force: true } prevents errors if the directory doesn’t exist. This method is preferred over the deprecated fs.rmdir() for modern Node.js versions and provides more robust directory removal.

Best Practice Note:

This is the same directory cleanup approach we use in CoreUI build tools for managing temporary files and output directories. Always use the force: true option to prevent errors when directories don’t exist, and consider using fs.promises.rm() with async/await for cleaner asynchronous code.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
The Wacky World of JavaScript: Unraveling the Oddities
The Wacky World of JavaScript: Unraveling the Oddities

How to Use Bootstrap Dropdown in Angular – CoreUI Integration Guide
How to Use Bootstrap Dropdown in Angular – CoreUI Integration Guide

How to force a React component to re-render
How to force a React component to re-render

How to Use Bootstrap Dropdown in React the Right Way – with CoreUI
How to Use Bootstrap Dropdown in React the Right Way – with CoreUI

Answers by CoreUI Core Team