| by Arround The Web | No comments

How to Delete Folders in Node.js?

Node.js comes with the “fs(File System)” built-in module that manipulates the operating system files or folders in a well-organized manner. The common features of this module are creating, accessing, searching, updating, renaming, and removing files or folders. This module performs all of the particular operations with the help of its pre-defined synchronous and asynchronous methods such as, “fs.mkdir()”, “fs.rmdir()”, “fs.access()”, “fs.accessSync()”, “fs.stat()”, “fs.statSync()”, “stats.isFile()”, and “stats.isFile()”.

This blog will demonstrate how to delete a folder in Node.js with the below-stated table of contents:

Let’s start with the “fs.rmdir()” method.

Method 1: Use “fs.rmdir()” to Delete a Folder in Node.js

The “fs.rmdir()” is the built-in asynchronous method of the “fs” module that deletes a particular folder placed at the given path. Its asynchronous nature does not stop the execution of all other operations while performing its specified task like deleting a folder.  

Syntax

The working of the “fs.rmdir()” method relies on its generalized syntax which is typed below:

fs.rmdir( path, options, callback )

 
The above syntax of the “fs.rmdir()” method supports the following three parameters:

    • path: It specifies the path and name of the folder that the user wants to delete.
    • options: It tells the new path and name of the folder that would be renamed with the old one.

 

Recursive It specifies a recursive boolean value that does not generate any error if the specified path does not contain the given folder. Its value is “false” by default.
maxRetries It represents an integer value that shows the number of times the deletion operation is performed on the failure.
retryDelay It also refers to an integer value that specifies a time delay in milliseconds before retrying the deletion operation.

 

    • callback: It executes after the completion of the “rmdir()” method. It supports the “err” parameter that throws an error if occurs during the method execution.

Example 1: Applying “fs.rename()” Method to Delete an Empty Folder Asynchronously

This example applies the “fs.rmdir()” method to delete an empty folder asynchronously.

First, look at the folder structure of the Node.js project before deleting the desired folder:


In the above folder structure, the highlighted “demoFolder” will be deleted. Let’s perform this task practically with the below-stated code block:

const fs = require('fs');
fs.rmdir("./demoFolder", (err) => {
if (err) {
console.error(err);
}else{
console.log("Folder deleted successfully");
}
});

 
In the above code lines:

    • Firstly, the “require()” method imports the “fs(File System)”.
    • Next, the “fs.rmdir()” method specifies the desired folder path as the first and the callback arrow function having the parameter “error” as the second parameter. This method deletes the specified folder and executes the given callback function on completion of the defined task.
    • In the callback function definition, an “if” statement uses the “console.error()” method to display the error message that occurs while deleting the specified folder.
    • If no error occurs, then the “else” statement will execute that utilizes the “console.log()” method to display the verification message.

Output

Initiate the “app.js” file using the below-stated command:

node app.js

 
The following output shows that the specified folder has been deleted successfully:


For more verification, look at the folder structure of the Node.js project. It can be seen that the “demoFolder” does not exist anymore in the root directory of the current node.js Project:


Example 2: Applying “fs.rename()” Method to Delete an Non-Empty Folder Asynchronously

If the specified folder that the user wants to delete is non-empty such as having some files and subdirectories then the “fs.rmdir()” generates the following error on its deletion:


To resolve this error the user can pass the “{recursive: true}” boolean value parameter to recursively delete the folder with the “fs.rmdir()” method.

Here is its practical implementation:

const fs = require('fs');
fs.rm("./myFolder", { recursive: true, force: true }, (err) => {
if (err) {
console.error(err);
}else{
console.log("Folder deleted successfully");
}
});

 
In the above code snippet:

  • The “fs.rmdir()” method passes the “{recursive: true}” parameter to delete the specified non-empty folder without generating any error.
  • The remaining code block is the same as in example 1.

Output

Run the “app.js” file:

node app.js

 
It can be observed that no error is generated on the deletion of a non-empty folder:

Method 2: Use “fs.rmdirSync()” to Delete a Folder in Node.js

The “fs.rmdirSync()” is a synchronous method that deletes the folders from the given specified path. Its synchronous behavior blocks the execution of all other operations until its specified task i.e. renaming a folder is not completed.

Syntax

The generalized syntax of the “fs.rmdirSync()” method is written below:

fs.rmdirSync( path, options )

 
The above syntax shows that the “fs.rmdirSync()” works only on the “path” and the “options” parameters defined in method 1.

Example: Applying “fs.rmdirSync()” Method to Delete a Folder

This example uses the “fs.rmdirSync()” method for deleting the specified empty folder from the current Node.js project:

const fs = require('fs');
fs.rmdirSync("./newFolder")
console.log("Folder deleted successfully");
var folder=fs.existsSync("./newFolder");
console.log("Folder exists:", folder);

 
In the above lines of code:

    • Firstly, “fs.rmdirSync()” method specifies the folder path and name that needs to be deleted.
    • Next, the “console.log()” method displays the verification message.
    • After that, the “folder” variable uses the “fs.existsSync()” method to indicate whether the given folder exists or not in the current directory.
    • Lastly, the “console.log()” statement displays the specified text statement in the console.

Output

Execute the “app.js” file:

node app.js

 
The output shows that the particular folder does not exist in the current directory because it has been deleted with the help of the “fs.rmdirSync()” method:

Method 3: Use “fsPromises.rmdir()” to Delete a Folder in Node.js

The “fsPromises.rmdir()” is another method that works the same as the “fs.rmdir()” by returning a promise. If the promise is resolved then it verifies that the specified folder is deleted. If any type of error occurs then the promise is rejected with an error object.

Syntax

The use of the “fsPromises.rmdir()” method depends on its basic syntax:

fsPromises.rmdir( path, options )

 
It can be seen that the “fsPromises.mdir()” method supports “path” and “options” parameters that perform the same functionality as defined in the “fs.rmdir()”.

Example: Applying the “fsPromises.rmdir()” Method to Delete a Folder

This example uses the “fsPromises.rmdir()” method to delete an empty folder:

const fsPromises = require('fs/promises')
getCurrentFilenames();
(async function main() {
try {
fsPromises.rmdir("./myFolder")
console.log("Folder Deleted!");
getCurrentFilenames();
} catch (err) {
console.error(err);
}
})();
function getCurrentFilenames() {
console.log("\nFolder Structure:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}

 
In the above code snippet:

    • Firstly, import the “fs” module from the “fs/Promises” to use the “async” versions of the “fs” methods.
    • Next, call the “getcurrentFilenames()” function.
    • After that, the “async” keyword makes the specified “main()” function a promise.
    • In this function definition, the “try” block applies the “fsPromises.rmdir()” method that deletes the specified folder. After that, it shows the verification message using the “console.log()” method and again calls the “getCurrentFilenames()
    • Now, the “catch” statement defines a code block that uses the “console.error()” method to display an error if it occurs.
    • Lastly, define the “getCurrentFilenames()” function.
    • In its definition, the “console.log()” method displays the specified text statement in the console.
    • The “readdirSync()” method and the concatenated “forEach()” function having a “file” argument retrieves the current directory structure along with all of its files and displays them in the console.

Output

Initiate the “app.js” file:

node app.js

 
The output shows that the promise of deleting an empty folder has been resolved successfully:


That’s all about deleting a folder in Node.js.

Conclusion

To delete a folder in Node.js, use the “fs.rmdir()”, “fs.rmdirSync()”, and the “fsPromises.rmdir()” built-in methods of the “fs(File System)” module. The “fs.rmdir()” method deletes a folder asynchronously and the “fs.rmdirSync()” removes a folder synchronously. Whereas, the “fsPromises.rmdir()” method deletes a folder as a promise. This blog has illustrated all possible methods to delete a folder in Node.js.

Share Button

Source: linuxhint.com

Leave a Reply