How to check if a file exists with Node.js

  1. Using the exists method
  2. Using the access method

In this article we’ll look at how to check if a file exists with Node.js

There are two methods you can use on the fs built in Node library to check if a file exists which you can use in a synchronous or asynchronous way.

Using the exists method

You can use the exists method to check if a file exists in a particular path.

Most of the time you’ll want to check if a file exists in a synchronous manner:

const fs = require('fs');
const path = __dirname + '/node.js'

try {
    if (fs.existsSync(path)) {
        console.log('File exists: Sync');
    }
} catch (error) {
    console.error(error);
}

Or you can use the exists method asynchronously:

const path = __dirname + '/node.js'

fs.exists(path, (exists) => {
    if (exists) {
        console.log('File exists async');
    }
});

Or even wrap it as a Promise if you want to include it in a promise chain:

const path = __dirname + '/node.js'
const { promisify } = require('util');

const existsPromise = promisify(fs.exists);

existsPromise(path)
    .then(exists => {
        if (exists) {
            console.log('File exists promise');
        }
    })
    .catch(error => {
        console.log(error);
    });

Using the access method

You can also use the access method to do the same thing but this actually tests the user’s permissions as to whether or not they can access the file.

Here’s the code if you want to use the access method:

const fs = require('fs');
const path = __dirname + '/node.js'
const { promisify } = require('util');

fs.access(path, fs.F_OK, (error) => {
    if (error) {
        console.log('Not exists');
    }

    console.log('Access File exists async');
});

const accessPromise = promisify(fs.access);

accessPromise(path, fs.F_OK)
    .then(() => {
        console.log('Access File exists promise');
    })
    .catch(error => {
        console.log(error);
    });


try {
    fs.accessSync(path, fs.F_OK);
    console.log('Access file exists sync');
} catch (err) {
    console.error('no access!');
}

You’ll need to pass in a particular file permission you want to check for e.g. fs.F_OK to check if the file can be accessed but you can also check for read/write access with fs.R_OK and fs.W_OK.