by Sai gowtham

Removing empty and non-empty directories in Node.js

In this tutorial, we are going to learn about how to remove an empty directory and non-empty directory that has files and folders in Node.js.

Removing the empty directory (or folder)

To remove an empty directory, we can use the fs.rmdir() method in Node.js.

The fs.rmdir() method works in an asynchronous manner that means non-blocking.

Example:

const fs = require('fs');

fs.rmdir('./images', (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("directory deleted successfully");
    }
})

The first argument in the fs.rmdir() method is a directory path (you want to remove) and second argument is the callback function that runs with an error argument.

Removing the Non-empty directory

Similarly, we can use the fs.rmdir() method to remove a directory that has files and folders by passing the recursive option as a second argument.

const fs = require('fs');

fs.rmdir('./junk', { recursive: true }, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("directory deleted successfully");
    }
})

Note: The recursive option is a experimental feature that requires node.js version 12 or higher.

There is also an npm package called rimraf, which helps us to remove the non-empty directories in easier way.

First, install the rimraf package by running the following command.

npm i rimraf

Usage:

const rimraf = require('rimraf');

rimraf('./junk', (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("directory deleted successfully");
    }
})

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course