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:
- 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
Javascript
let fs = require( 'fs' );
getCurrentFilenames();
fs.rmSync( './dummy.txt' );
getCurrentFilenames();
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
Javascript
const fs = require( 'fs' );
getCurrentFilenames();
fs.rmSync( "./build" , { recursive: true });
getCurrentFilenames();
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
Last Updated :
03 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...