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");
}
})