Open In App

Node.js fs-extra pathExists() Function

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:

Return value: It does not return anything.



Follow the steps to implement the function:

  1. The module can be installed by using the following command:

    npm install fs-extra

  2. After the installation of the module you can check the version of the installed module by using this command:

    npm ls fs-extra

  3. 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');
  4. 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:




// 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:




// 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.


Article Tags :