You can check if a file exists inside a folder using the Node.js fs
module. It is useful before deleting or renaming a file in NodeJS. Because you need to make sure that the file exists before using it.
Node.js has 3 methods in the fs
module to check if a file exists inside a folder. To check synchronously, it has fs.existsSync()
and fs.accessSync()
methods. We can also confirm a file asynchronously using fs.access()
method.
I will explain all of these methods in this article step by step with examples. You can choose any of them for your future projects according to the requirements.
Note: There is a
fs.exists()
method in thefs
module. But this method is deprecated, that's why it is not recommended to use. NodeJS suggests to use thefs.access()
method instead.
Synchronously Check If a File Exists Using fs.existsSync()
It is the easiest way to confirm whether a file exists inside a folder using the Node.js fs.existsSync()
method. This method accepts the path of that file as its argument.
It will return true
if the file exists, false
otherwise. Let's see an example.
const fs = require('fs');
if (fs.existsSync('./img/banner.jpg')) {
console.log('File exists');
} else {
console.log('File does not exist');
}
You have to access this method from the fs
module in NodeJS. I am calling the existsSync()
method from that module.
I have an img
folder and I want to check whether this folder contains the banner.jpg
file or not. That's why I have to provide the path of that file when I call the fs.existsSync()
method.
If the banner.jpg
file is present inside the img
folder, the if
block will run. On the other hand, if the folder doesn't have the file, the else
block will execute.
It is important to note that this method will execute synchronously. That means it will block the main thread and stop the execution of other JavaScript code until this method completes the task.
That's why most of the time, it is good to use asynchronous methods. If you want to understand the differences between synchronous and asynchronous programming with examples, we have a complete guide on this topic.
Asynchronously Check If a File Exists Using fs.access()
To check whether a folder has a specific file or not in Node.js asynchronously, you can use the fs.access()
method. Unlike a synchronous method, it will not block the main thread.
You can apply this method in two ways:
- Method 1: Using promise and async/await syntax.
- Method 2: Using callback syntax.
I will show both methods so that you can choose depending on the method you like. Let's start with the first technique.
Method 1: Using promise and async/await syntax.
When we require the promised version of the fs
module, the fs.access()
method will return a promise. Then we can handle it using async/await syntax in JavaScript.
const fs = require('fs').promises;
const checkFile = async (path) => {
try {
await fs.access(path);
console.log('File exists');
} catch (error) {
// Handle error here
console.log("File doesn't exists");
}
};
checkFile('./img/banner.jpg');
I am getting the promised version of the fs
module from NodeJS. I am also creating an async function because we must use the await keyword inside an async function.
Finally, we need to call the function manually. You can also use a self-invoking function if you prefer. In that case, JavaScript will automatically execute that function.
You can call the fs.access()
method with the await keyword inside the function. It accepts 2 parameters. The first parameter is the path of the file that you want to check.
The second parameter is optional. Here we can provide the file access constants from NodeJS. The default value is fs.constants.F_OK
.
The fs.constants.F_OK
is used to determine if a file exists. You can identify if a file is readable or writable by using other constants. There are 4 of them.
You can handle the possible errors with a try...catch
block. This method returns no value. If it finds the file the try
block will run. Otherwise, it will throw an error saying "no such file or directory", this will execute the catch
block.
Method 2: Using callback syntax.
If you don't want to use the promised version with the async/await syntax, you can use a callback with the fs.access()
method.
In this case, we need to require the regular fs
module from Node.js and call this method from it. Now we can pass 3 parameters instead of 2.
const fs = require('fs');
fs.access('./img/banner.jpg', fs.constants.F_OK, (error) => {
if (error) {
// Handle error here
console.log("File doesn't exist");
} else {
console.log('File exists');
}
});
When you call this method, you have to give the path of a file. The second parameter is optional where it accepts the file access constants with fs.constants.F_OK
as a default value.
You can remove this parameter if you want. Finally, it takes a callback function. If there is no file in that path, this function will give the error
object, it will be null
otherwise.
Also Read: How to Get All Files in Directories (Recursively) with Node.js
Use fs.accessSync() to Check If a File Exists Synchronously
There is a fs.accessSync()
method in the fs module to determine the existence of a file. Unlike the fs.existsSync()
method, it doesn't return a true or false value.
If it doesn't find the file, it will throw an error. That's why we need to use the try...catch
block to handle the error.
const fs = require('fs');
try {
fs.accessSync('./img/banner.jpg', fs.constants.F_OK);
console.log('File exists');
} catch (error) {
// Handle error here
console.log("File doesn't exists");
}
The fs.accessSync()
method has 2 parameters. The first parameter accepts the path of a file and the second parameter is optional for file access constants.
As I said earlier, If there is a file in that path, the try
block will run. But when this method doesn't get that file, it will throw an error that will trigger the catch
block.
Also Read: Easy Ways to Download Any File From Node.js Server Using Express
Conclusion
I have tried to give you in-depth information about finding the existence of a file. If I summarize the whole topic, we will find that there are 3 methods in the fs module to solve the problem.
We can use the fs.access()
method when we want to determine if a file exists along with specific permissions asynchronously.
But if you want to do this synchronously, you will have 2 options. You can either use the fs.existsSync()
or fs.accessSync()
method.
The fs.existsSync()
is the easiest between the two of them. It is recommended to use the fs.existsSync()
method to check if a file exists inside a folder with the Node.js fs
module.