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}.`);
}

The recursive option is still experimental and requires Node.js version 12 and higher. 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 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 @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.