Open In App

Node.js fs.rmSync() Method

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

Syntax:



fs.rmSync( path, options );

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

Below examples illustrate the fs.rmSync() method in Node.js:



Example 1: This example uses fs.rmSync() method to delete a file.

Filename: index.js




// Import necessary modules
let fs = require('fs');
  
// List files before deleting
getCurrentFilenames();
  
fs.rmSync('./dummy.txt');
  
// List files after deleting
getCurrentFilenames();
  
// This will list all files in current directory
function getCurrentFilenames() { 
    console.log("\nCurrent filenames:"); 
    fs.readdirSync(__dirname).forEach(file => { 
        console.log(file); 
    }); 
    console.log(""); 
}

Run the index.js file using the following command:

node index.js

Output:

Current filenames:
dummy.txt
index.js
node_modules
package-lock.json
package.json


Current filenames:
index.js
node_modules
package-lock.json
package.json

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

Filename: index.js




// Import the filesystem module 
const fs = require('fs'); 
    
// List the files in current directory 
getCurrentFilenames(); 
  
// Using the recursive option to delete directory 
fs.rmSync("./build", { recursive: true });
  
// List files after delete 
getCurrentFilenames(); 
    
// List all files in current directory
function getCurrentFilenames() { 
  console.log("\nCurrent filenames:"); 
  fs.readdirSync(__dirname).forEach(file => { 
    console.log(file); 
  }); 
  console.log("\n"); 
}

Run the index.js file using the following command:

node index.js

Output:

Current filenames:
build
index.js
node_modules     
package-lock.json
package.json

Current filenames:
index.js
node_modules
package-lock.json
package.json

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


Article Tags :