Introduction

In Node.js, checking whether a file exists is a common operation in file handling. This document explains different methods to check file existence using both synchronous and asynchronous approaches.

Prerequisites

Before proceeding, ensure that you have Node.js installed on your system. You can verify this by running:
node -v

Methods to Check File Existence

1. Using fs.existsSync (Synchronous Method)

The fs.existsSync method is a simple way to check if a file exists synchronously.

Implementation:

const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');

if (fs.existsSync(filePath)) {
    console.log('File exists');
} else {
    console.log('File does not exist');
}

Explanation:

  • fs.existsSync(filePath) checks if the file exists.
  • The method returns true if the file exists; otherwise, it returns false.
  • This method is blocking and should not be used in performance-critical applications.
Also Read

Also Read:

Node JS Multer

2. Using fs.promises.access (Asynchronous Method)

The fs.promises.access method provides an asynchronous way to check file existence.
Implementation:

const fs = require('fs').promises;
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');

async function checkFile() {
    try {
        await fs.access(filePath);
        console.log('File exists');
    } catch (error) {
        console.log('File does not exist');
    }
}
checkFile();

Explanation:

  • fs.access(filePath) checks if the file exists.
  • If the file exists, no error is thrown, and “File exists” is logged.
  • If the file does not exist, an error is caught in the catch block, logging “File does not exist”.
  • This method is non-blocking and recommended for asynchronous applications.

Choosing the Right Method

Method Blocking Recommended for
fs.existsSync Yes Simple, quick checks in scripts
fs.promises.access No Asynchronous applications

Conclusion

Both synchronous and asynchronous methods are available to check if a file exists in Node.js. While fs.existsSync is straightforward, fs.promises.access is preferred for non-blocking operations.

Need Help With Node Development?

Work with our skilled Node developers to accelerate your project and boost its performance.

Hire Node.js Developers

Support On Demand!

Related Q&A