Saturday, January 31, 2026
HomeLanguagesJavascriptNode.js fs-extra pathExists() Function

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:

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

  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:

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.

RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS