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 theexists()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.
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
fsmodule and create anfsobject. -
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 theexists()function is executed, this parameter will returntrueif the file is in the directory andfalseif the file does not exist.
-
-
In line 4, we check the condition
true. If the function gets the file, it returnstrue, so theifblock will run. -
In line 5, we print the text when the file is found.
-
In line 7, we have an
elseblock after theifblock to handle the case where theexists()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.