What is the Node fs.exists() method?

Overview

In this shot, we will learn about the exists() method provided by the fs module, which checks if the given file or path exists in the directory.

Syntax

fs.exists(Path/FileName, Callback())

Parameters

  • Path/FileName: Full path or the name of the file.

  • Callback(): Callback function for the exists() method.

Return value

The method returns a boolean value. exists() returns true if the file or path exists in the directory, and false if the file or path does not exist.

Code

We will write a sample code to illustrate how to use the fs.exists method.

We will create another empty text file (demo.txt) in the same directory.

index.js
demo.txt
var fs = require('fs');
fs.exists('demo.txt', (file) => {
if(file){
console.log('File Found');
}
else{
console.log('File Not Found');
}
});

Code explanation

  • In line 1, we import the fs module and create an fs object.

  • In line 3, we use the fs.exists() method to find a file by passing 2 parameters:

    • /demo.txt: Full path or the name of the file.

    • callback(File): After the exists() function is executed, this parameter will return true if the file is in the directory and false if the file does not exist.

  • In line 4, we check the condition true. If the function gets the file, it returns true, so the if block will run.

  • In line 5, we print the text when the file is found.

  • In line 7, we have an else block after the if block to handle the case where the exists() function does not find the file.

  • In line 8, we print the text if the file is not found or does not exist.

Output

When we click the run button, we get File Found as a result because the director and path have a file named demo.txt. If we delete this file or pass any other path/filename in the exists method, then we will get the output File Not Found because it is not in the directory of the file structure.