Node.js fs.rmSync() Method
Last Updated :
03 Feb, 2021
Improve
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:
- path: It holds the path of the file that has to be removed. It can be a String, Buffer, or URL.
- options: It is an object that can be used to specify optional parameters that will affect the operation as follows:
- force: It is a boolean value. Exceptions will be ignored if the path does not exist.
- recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
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.jsonReference:https://nodejs.org/api/fs.html#fs_fs_rmsync_path_options