Yhe remove() function deletes the given file or directory. All the files inside a directory are deleted. If the given file or directory does not exist the function will do nothing.
Syntax:
fs.remove(path,callback)
Parameters: This function accepts two parameters as mentioned above and described below.
- path: It is a string that contains the file path or directory path.
- callback: It will be called after the function is executed. We can use promises in place of the callback function as well.
Return value: It does not return anything.
Follow the steps to implement the function:
The module can be installed by using the following command:
npm install fs-extra
After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
Create a file with the name index.js and require the fs-extra module in the file using the following command:
const fs = require('fs-extra');
To run the file write the following command in the terminal:
node index.js
The project structure will look like this:
Example 1:
index.js
// Requiring module
import { remove } from
"fs-extra"
;
// This file exists
// already so the
// function will delete it
const file =
"file.txt"
;
// Function call
// Using callback function
fs.remove(file, (err) => {
if
(err)
return
console.log(err);
console.log(
"Given file is deleted"
);
});
Output: This output will be a console output.
Example 2:
index.js
// Requiring module
import { remove } from
"fs-extra"
;
// The directory and
// the files inside
// it will be deleted
const file =
"dir"
;
// Function call
// Using Promises
remove(file)
.then(() => console.log(
"Directory and files inside it are deleted"
))
.
catch
((e) => console.log(e));
Output: This output will be a console output.
Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/remove.md