The simplest way to check if a file exists in the file system is by using the fs module's fs.existsSync() method. It returns true if the path exists, false otherwise:

const fs = require('fs');

try {
    if(fs.existsSync('file.txt')) {
        console.log("The file exists.");
    } else {
        console.log('The file does not exist.');
    }
} catch (err) {
    console.error(err);
}

This method is synchronous which means it will block the execution until the operation is completed.

fs.access() Method

If you want to check if the file exists asynchronously, use fs.access() method instead. It is the non-blocking way of checking the file existence without opening it:

const fs = require('fs');

fs.access('file.txt', (err) => {
    if (err) {
        console.log("The file does not exist.");
    } else {
        console.log("The file exists.");
    }
});

The fs.access() method takes three arguments:

  • path — The file or directory path for testing the user's permissions.
  • mode — An optional integer that specifies the accessibility check to be performed. The default value is fs.constants.F_OK
  • callback — The callback function that is invoked with a possible error object in case if any of the accessibility checks fail.

In addition to checking the file existence, you can even use fs.access() method to check if the file is readable or writable by passing different File Access Constants:

const fs = require('fs');

const file = 'file.txt';

// check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
    console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});

// check if the file is readable.
fs.access(file, fs.constants.R_OK, (err) => {
    console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});

// check if the file is writable.
fs.access(file, fs.constants.W_OK, (err) => {
    console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});

// Check if the file exists in the current directory, and if it is readable.
fs.access(file, fs.constants.F_OK | fs.constants.R_OK, (err) => {
    if (err) {
        console.error(
            `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
    } else {
        console.log(`${file} exists, and it is readable`);
    }
});

fs.accessSync() Method

Similar to fs.existsSync() method, the fs.accessSync() method checks the file existence synchronously but without opening it:

const fs = require('fs');

try {
    fs.accessSync('file.txt', fs.constants.F_OK);

    console.log("The file exists.");
} catch (err) {
    console.error(err);
}

Read Next: Reading and Writing Files in Node.js

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: