how to check if file exists in nodejs

How to Check If a File Exists in Node.js

In this short tip post, we will learn how to check if a file exists in the filesystem using Node.js file system (fs) module.

Objective

Figuring out the best way to check the existence of a file in a system using the native file system module of Node.

Approach

One of the simplest approach to check whether the file exists or not is by using the readFile() function. However, this function does open the file descriptor and takes some memory too.

If you just want to check the file existences in the system, I highly recommend the access() function.

Code

Here is the code.

const fs = require('fs');

const path = './config.js';

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err);
    return;
  }
  // file exists
});

If you want to avoid callback, we can always use promises and async/await. Like this.

const fs = require('fs')

function fileExist(filePath) {
 return new Promise((resolve, reject) => {
   fs.access(filePath, fs.F_OK, (err) => {
     if (err) {
       console.error(err)
       return reject(err);
    }
     //file exists
     resolve();
   })
 });
}
const path = './file.txt';
async function main() {
  let existFlag = await fileExist(path);
}

Love Node.js? Check out our vast amount of Node.js articles and tutorials.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

1 Comment

  1. I got
    { [Error: ENOENT: no such file or directory, access ‘config.js’]
    errno: -2,
    code: ‘ENOENT’,
    syscall: ‘access’,
    path: ‘config.js’ }
    after using your code

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.