NodeJS is a powerful JavaScript framework to help you build web applications and website using JavaScript. It provides many functions to work with files. Most often, you may need to check if a file exists in NodeJS. If you try to access a file that does not exist, NodeJS will give an error and your code may stop working. In this article, we will learn how to check if file exists in NodeJS.
How to Check if File Exists in NodeJS
Here are the steps to check if file exists in NodeJS.
NodeJS provides fs module to access file system. Let us say you want to test if the following file path exists.
path = '/home/ubuntu/test.txt'
First, we import this module.
const fs = require("fs");
Now there are two ways to check if a file exists – synchronous way and asynchronous way. We will look at both these methods one by one.
1. Synchronous File Check
In this case, you can easily check if a file exists with the existsSync() function, which returns true if the file path exists and false if the file path does not exist.
if (fs.existsSync(path)) { // file exists }else{ // file does not exist }
2. Asynchronous File Check
You can also do an asynchronous check using fs.promises.access or fs.access.
try { await fs.promises.access(path); // file exists } catch (error) { // file does not exist }
Alternatively, you can also check it with a callback.
fs.access("somefile", error => { if (!error) { // file exists } else { // file does not exist } });
In this article, we have learnt several ways to check if file exists or not in NodeJS. You can use any of them depending on your requirement.
Please note, the fs module is frequently updated and sometimes the functions mentioned above might become deprecated. If you find that to be the case, please let us know in comments and we will update this article immediately.
Also read:
How to Load Local JSON File
How to Show Loading Spinner in jQuery
How to Convert String to Boolean in JS
How to Convert Decimal to Hex in JS
How to Add 30 Minutes to JS Date
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.