How to Check If a File Exists in Node.js

how to check if file exists in nodejs

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.


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


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.


Here is the code.

const fs = require('fs');

const path = './config.js';

fs.access(path, fs.F_OK, (err) => {
  if (err) {
  // 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) {
       return reject(err);
     //file exists
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.

1 thought on “How to Check If a File Exists in Node.js”

  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

Comments are closed.