VOOZH about

URL: https://www.geeksforgeeks.org/node-js/node-js-fs-rm-method/

⇱ Node.js fs.rm() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Node.js fs.rm() Method

Last Updated : 3 Feb, 2021

The fs.rm() method is used to delete a file at the given path. It can also be used recursively to remove directories.

Syntax:

fs.rm( path, options, callback );

Parameters: This method accepts three 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 that 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.
  • callback: It is the function that would be called when the method is executed.
    • err: It is an error that would be thrown if the operation fails.

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

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

Filename: index.js

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

File deleted successfully

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

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

Filename: index.js

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

SystemError [ERR_FS_EISDIR]: Path is a directory: rm returned EISDIR 
(is a directory) ./build
 at internal/fs/utils.js:688:23
 at FSReqCallback.oncomplete (fs.js:184:5) {
 code: 'ERR_FS_EISDIR',
 info: {
 code: 'EISDIR',
 message: 'is a directory',
 path: './build',
 syscall: 'rm',
 errno: 21
 },
 errno: [Getter/Setter: 21],
 syscall: [Getter/Setter: 'rm'],
 path: [Getter/Setter: './build']
}

Recursive: Directory Deleted!

Current filenames:
index.js
node_modules
package-lock.json
package.json
Reference:https://nodejs.org/api/fs.html#fs_fs_rm_path_options_callback
Comment

Explore