fs.rmdir vs. fs.rmdirSync in Node.js
The fs module is a built-in file system module in Node.js that consists of several methods that can be used to access and manipulate files on the operating system. rmdir() and rmdirSync() are fs methods used to remove an empty and existing directory.
Note: If you want to remove a non-empty directory, use
rimraf.sync().
Difference between the two methods
The main difference between the two methods is that rmdir() is an asynchronous method and rmdirSync() is a synchronous method.
Let's look at their key differences and get a basic idea of when to use which method.
Key differences
rmdir() | rmdirSync() | |
Asynchronous vs. Synchronous | It is asynchronous. That means when this function is called, it will execute and remove an empty directory while the other code continues to execute. | It is synchronous. That means when this function is called, it will execute and remove an empty directory and send a callback. Till then the system will go in waiting and nothing else is executed. |
Syntax | Use if–else to handle cases. | Use try–catch to handle cases. |
When to use | Used when there is a need to handle non-blocking requests. Hence, no immediate need to remove the directory. | Used where there is a need for a blocking request to ensure immedate directory removal. |
Real life example | We can delete a user file in a web application asynchronously, allowing the website to respond while it simultaneously handles remove requests. | We can remove directories synchronously when performing a clean up operation to ensure the directory is removed completely before the script exits. |
Required import
Import the Node.js package fs to access files:
const fs = require('fs')
Syntax
The parameters for the fs.rmdir() and fs.rmdirSync() methods are the same, with a slight difference in syntax.
The syntax for fs.rmdir() when handling its cases using if–else conditions:
fs.rmdir('./path/directoryName', (error) => {if(error){}else{}});
The syntax for fs.rmdirSync() when handling its cases using try–catch block:
try { fs.rmdirSync('./path/directoryName');} catch (error){}
Parameters
path:The destination of the directory that is to be removed.directoryName: The name of the directory that is to be removed.error:A callback function that is called once the method is executed and returns one of the two cases:error: The method failed to remove the specified directory.null: The method successfully removed the specified directory.
Example code
This code shows the syntax of both methods for removing an empty directory. In this case, public directory contains test.txt file and two empty directories: SyncDir and AsyncDir.
//required importconst fs = require('fs');console.log("\nFile in current directory")console.log(fs.readdirSync("./public"));//removing empty directory asynchronouslyfs.rmdir('./public/AsyncDir' , (error) => {if (error) {console.log(err);} else {console.log('\nDirectory removed successfully asynchronously.');}});console.log("\nFile in current directory")console.log(fs.readdirSync("./public"));//removing empty directory synchronouslytry {fs.rmdirSync('./public/SyncDir');console.log('\nDirectory removed successfully synchronously.');} catch (error) {console.log(error);}console.log("\nFile in current directory")console.log(fs.readdirSync("./public"));
Output explanation
Let's understand the output of the above example code and examine the difference in the behavior of a synchronous and asynchronous function.
Contents of the
publicdirectory are printed and containsAsyncDir,SyncDirandtest.txt.Contents of the
publicdirectory are printed again after thermdir()method is called. Note that no callback is received, but theAsyncDirdirectory is removed frompublicdirectory.The
rmdirSync()method is executed, and its success case statement is printed immediately as the proceeding code does not execute until and unless a callback for a synchronous method is received.Contents of the
publicdirectory are again printed to check thermdirSync()method's change since we already received a successful callback from it. Notice that theSyncDirdirectory is removed frompublicdirectory.The success case statement of the
rmdir()method is printed once all the other code has been executed.
Common query
Can we remove a non-empty directory through rmdir() method?
Free Resources