How to delete directories in Node.js

Deleting directories in Node.js enables cleanup operations, temporary folder management, and automated file system maintenance through built-in filesystem module methods. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented directory deletion in countless Node.js applications for build cleanup, temporary file management, and automated maintenance scripts. From my expertise, the most effective approach is using fs.rm() with recursive options for modern Node.js or fs.rmdir() for older versions with proper error handling. This method provides safe directory removal with comprehensive error management and support for nested directory structures.

Use fs.rm() with recursive option for modern Node.js or fs.rmdir() for removing directories safely.

import { rm, rmdir, access } from 'fs/promises'
import { constants } from 'fs'

// Modern approach: fs.rm() with recursive (Node.js 14.14.0+)
async function deleteDirectory(dirPath) {
  try {
    await rm(dirPath, { recursive: true, force: true })
    console.log(`Directory ${dirPath} deleted successfully`)
  } catch (error) {
    console.error('Error deleting directory:', error.message)
  }
}

// Legacy approach: fs.rmdir() for older Node.js versions
async function deleteDirectoryLegacy(dirPath) {
  try {
    await rmdir(dirPath, { recursive: true })
    console.log(`Directory ${dirPath} deleted successfully`)
  } catch (error) {
    if (error.code === 'ENOENT') {
      console.log('Directory does not exist')
    } else {
      console.error('Error deleting directory:', error.message)
    }
  }
}

// Safe deletion with existence check
async function safeDeleteDirectory(dirPath) {
  try {
    await access(dirPath, constants.F_OK)
    await rm(dirPath, { recursive: true, force: true })
    console.log(`Directory ${dirPath} deleted successfully`)
  } catch (error) {
    if (error.code === 'ENOENT') {
      console.log('Directory does not exist')
    } else {
      console.error('Error deleting directory:', error.message)
    }
  }
}

// Delete only if empty
async function deleteEmptyDirectory(dirPath) {
  try {
    await rmdir(dirPath)  // Without recursive option
    console.log(`Empty directory ${dirPath} deleted`)
  } catch (error) {
    if (error.code === 'ENOTEMPTY') {
      console.log('Directory is not empty')
    } else {
      console.error('Error deleting empty directory:', error.message)
    }
  }
}

// Batch directory deletion
async function deleteMultipleDirectories(dirPaths) {
  const results = await Promise.allSettled(
    dirPaths.map(path => rm(path, { recursive: true, force: true }))
  )

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`${dirPaths[index]} deleted successfully`)
    } else {
      console.error(`Failed to delete ${dirPaths[index]}:`, result.reason.message)
    }
  })
}

// Example usage
await deleteDirectory('./temp-folder')
await safeDeleteDirectory('./build-output')
await deleteMultipleDirectories(['./temp1', './temp2', './cache'])

The fs.rm() method with recursive: true option removes directories and all their contents. Use force: true to ignore ENOENT errors for non-existent paths. For older Node.js versions, use fs.rmdir() with recursive option. Handle ENOENT and ENOTEMPTY errors appropriately based on your use case.

Best Practice Note:

This is the same directory deletion approach we use in CoreUI Node.js build scripts for cleaning temporary files and managing build artifacts in automated workflows.


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.
How to disable a button in JavaScript
How to disable a button in JavaScript

How to Remove Underline from Link in CSS
How to Remove Underline from Link in CSS

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

How to Center a Button in CSS
How to Center a Button in CSS

Answers by CoreUI Core Team