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
// Requiring module const fs = require( "fs-extra" ); // This file already // exists so function // will return true const file = "file.txt" ; // Function call // Using callback function 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
// Requiring module const fs = require( "fs-extra" ); // This file doesn't // exists so function // will return false const file = "dir/file.txt" ; // Function call // Using Promises fs.pathExists(file) .then((exists) => console.log(exists)) . catch ((e) => console.log(e)); |
Output: This will be the console output.