In a Node.js application, you can use the fs.rmdir() method to delete a directory. This method works asynchronously to remove the directory. If the directory is not empty, you can pass an optional recursive flag to delete all nested files and folders recursively.

Here is an example:

const fs = require('fs')

// directory path
const dir = 'temp'

// delete directory recursively
fs.rmdir(dir, { recursive: true }, err => {
  if (err) {
    throw err
  }

  console.log(`${dir} is deleted!`)
})

The fs module also contains a synchronous variant of the rmdir() method called rmdirSync() that removes the given folder synchronously. It blocks the Node.js event loop execution until the delete operation is not completed.

Let us look at the below example that deletes a folder synchronously:

const fs = require('fs')

// directory path
const dir = 'temp'

// delete directory recursively
try {
  fs.rmdirSync(dir, { recursive: true })

  console.log(`${dir} is deleted!`)
} catch (err) {
  console.error(`Error while deleting ${dir}.`)
}

In Node.js v16.x, the recursive option is depreciated for the fs.rmdir() method. Instead, use the fs.rm() method to delete non-empty folders:

const fs = require('fs')

// directory path
const dir = 'temp'

// delete directory recursively
fs.rm(dir, { recursive: true, force: true }, err => {
  if (err) {
    throw err
  }

  console.log(`${dir} is deleted!`)
})

If you using an older version of Node.js, just use the del module from the NPM registry.

The del module is, by far, the easiest, safest, and most cross-platform option available to remove non-empty directories in Node.js. It provides a modern JavaScript API and supports both promises and async-await syntax.

Install the del module by running the following command in your terminal:

$ npm install del --save

Here is an example that demonstrates how to use the del module to delete a directory recursively:

const del = require('del')

// directory path
const dir = 'temp'

// delete directory recursively
;(async () => {
  try {
    await del(dir)

    console.log(`${dir} is deleted!`)
  } catch (err) {
    console.error(`Error while deleting ${dir}.`)
  }
})()

To move the directory to the trash instead of deleting it permanently, you can use the trash package which only moves files and folders to the trash.

Take a look at this guide to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.