All Articles

How to check if a file exists in Node.js

Image of Node JS with Black background

With the fs module in Node.js you can check if a file exists by using the synchronous fs.existsSync(path) method which has the following signature:

function existsSync(path: PathLike): boolean;

The following snippet shows how you would use this in code. It is important to note that this is “blocking” because fs.existsSync is synchronous.

const fs = require('fs');

if(fs.existsSync('path-to-your-file')) {
  // file exists. Let's do something with it
}

It is usually advisable to make use of Node.js’ asynchronous methods. There used to be fs.exists but that is deprecated, instead you can use the fs.stat(path) method. It has this signature:

function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;

This is how you might use it in your code:

fs.stat('./packages.json', (err, status) => {
  if(err) {
    if(err.code === 'ENOENT') {
      // file doesn't exist
    }
    // handle other potential errors here
  }

  // file exists, do something with the file
})

You could also use the fs.access(path) method:

function access(path: PathLike, callback: NoParamCallback): void;
fs.access('./packages.json', (err) => {
if(err) {
  // file doesn't exist
}

// file exists
});