Open In App

Node.js fs.rmdirSync() Method

The fs.rmdirSync() method is used to synchronously delete a directory at the given path. It can also be used recursively to remove nested directories by configuring the options object. It returns undefined.
Syntax: 
 

fs.rmdirSync( path, options )

Parameters: This method accept two parameters as mentioned above and described below: 
 



Below examples illustrate the fs.rmdirSync() method in Node.js:
Example 1: This example uses fs.rmdirSync() method to delete a directory.
 




// Node.js program to demonstrate the
// fs.rmdirSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the current filenames
// in the directory
getCurrentFilenames();
  
fs.rmdirSync("directory_one");
console.log("Folder Deleted!");
  
// Get the current filenames
// in the directory to verify
getCurrentFilenames();
  
// Function to get current filenames
// in directory
function getCurrentFilenames() {
  console.log("\nCurrent filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
  // console.log("\n");
}

Output: 
 



Current filenames:
directory_one
index.js
package.json
Folder Deleted!

Current filenames:
index.js
package.json

Example 2: This example uses fs.rmdirSync() method with the recursive parameter to delete nested directories.
 




// Node.js program to demonstrate the
// fs.rmdirSync() method
  
// Get the current filenames
// in the directory
getCurrentFilenames();
  
// Using the recursive option to delete
// multiple directories that are nested
fs.rmdirSync("directory_one", {
  recursive: true,
});
console.log("Directories Deleted!");
  
// Get the current filenames
// in the directory to verify
getCurrentFilenames();
  
  
// Function to get current filenames
// in directory
function getCurrentFilenames() {
  console.log("\nCurrent filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
  console.log("\n");
}

Output: 
 

Current filenames:
directory_one
index.js
package.json


Directories Deleted!

Current filenames:
index.js
package.json

Reference: https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path_options
 


Article Tags :