Node.js fs-extra pathExists() Function
Last Updated :
07 Oct, 2021
The pathExists() tests whether the given file path exists or not. It uses the fs.access() under the hood.
Syntax:
fs.pathExists(file,callback)
Parameters: This function accepts two parameters as mentioned above and described below:
- file: It is a string that contains the file path.
- callback: It will be called after the function is executed. It will either result in an error or a boolean value called exists. 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
Project Structure: The project structure will look like this:
Example 1:
index.js
const fs = require( "fs-extra" );
const file = "file.txt" ;
fs.pathExists(file, (err, exists) => {
if (err) return console.log(err);
console.log(exists);
});
|
Output: This will be the console output.
Example 2:
index.js
const fs = require( "fs-extra" );
const file = "dir/file.txt" ;
fs.pathExists(file)
.then((exists) => console.log(exists))
. catch ((e) => console.log(e));
|
Output: This will be the console output.
Share your thoughts in the comments
Please Login to comment...