How to Check If a File Exists in Node.js

Whenever there is a need to interact with a file, it is recommended to first check whether the file exists or not. For example, if you’re trying to read or write on a file that doesn’t exist, you’ll be getting an error, and if it’s a real-time live application, think of it as a user, it can be frustrating, especially if it botches the operation. That’s why checking file existence is important before performing any operation. This tutorial will help you to learn how to check that.

In this tutorial we will start with a file system module that has methods to check if a file exists, then we will implement both synchronous and asynchronous ways of doing this, and then for further customization, we will use the async/await to create a function so that you can reuse it directly through a Node.js program when it is needed to check for a file existence. Let’s get started.

Node File System Module

File System provides API to interact with files. Using Node.js File System, operations like creating, reading, detecting and deleting files are done. This module has four methods for checking for the existence of files, all with synchronous and asynchronous versions that can be used depending on requirements.

Let us first see how to import FS module in Node.js.

Syntax:

const fs = require('fs');

Node.js File System is a built-in module that we can directly import inside our project to use. There is no need to install it manually.

Synchronously check if a File Exists in Node.js

The FS synchronous method can be useful when there is a need to block the execution of the rest of the program until the path of the file is found.

Following are the methods that can synchronously check if the file exists or not:

  1. fs.existsSync()
  2. fs.statSync()
  3. fs.accessSync()
  4. fs.readdirSync()

Let’s see them one by one.

fs.existsSync(path)

This method takes a filepath as an argument to check for the existence of the file, if it does not exit it throws an error which we can handle using if/else blocks.

Example:

const fs = require('fs');

const path = './example.txt';

if (fs.existsSync(path)) {
  console.log('File exists');
} else {
  console.log('File does not exist');
}

For this and other examples of this tutorial, remember we have an “example.txt” file in the current working directory.

Output:

File exists

fs.statSync(path)

This method is similar but additionally returns an “fs.Stats” object containing information about the file if it exists.

Example:

const fs = require('fs');

const path = './example.txt';

try {
  const stats = fs.statSync(path);
  console.log('File exists');
} catch (err) {
  console.log('File does not exist');
}

Here we have try/catch block because this method does not throw an error if the file does not exist. Instead, it returns an error object that can be handled using a try/catch block.

Output:

File exists

fs.accessSync(path, mode)

This method takes an additional parameter after the file path, which is “fs.constants.F_OK” which is important to pass to check the existence of a file.

Example:

const fs = require('fs');

const filePath = './example.txt';

try {
  fs.accessSync(filePath, fs.constants.F_OK);
  console.log('File exists');
} catch (err) {
  console.log('File does not exist');
}

Output:

File exists

fs.readdirSync()

The fs.readdirSync() method in NodeJS is used to list the contents of a directory. We can use the includes() method with it to check if a file exists in a specified directory.

Example:

const fs = require('fs');

const path = './';

fs.readdir(path, (err, files) => {
  if (err) {
    console.log('Directory does not exist.');
  } else if (files.includes('example.txt')) {
    console.log('File exists.');
  } else {
    console.log('File does not exist.');
  }
});

Output:

File exists

Note: These methods do not return false if the file doesn’t exist. Instead, they either throw an error or return an error object

Asynchronously check if a File Exists in Node.js

Asynchronous methods are useful when we don’t want to block the execution of another program while it waits for the file to check, additionally, its callback makes handling errors much easier.

Following are the methods that can asynchronously check if the file exists or not:

  1. fs.exists()
  2. fs.stat()
  3. fs.access()
  4. fs.readdir()

Let’s see them one by one.

fs.exists(path, callback)

This method is straightforward, it takes the path of a file to check for existence and a callback function having a parameter that will result boolean true if the file exists.

Note: It is not recommended to use this because this method is deprecated, but it can still be used.

Example:

const fs = require('fs');

const path = './example.txt';

fs.exists(path, (exists) => {
  if (exists) {
    console.log('File exists');
  } else {
    console.log('File does not exist');
  }
});

Output:

File exists

fs.stat(path, callback)

This method returns an object when the file exits. The object has various properties like “dev”, “mode”, “nlink”, “size”, etc.

Example:

const fs = require('fs');

const path = './example.txt';

fs.stat(path, (err, stats) => {
  if (err) {
    console.log('File does not exist');
  } else {
    console.log('File exists');
  }
});

Output:

File exists

fs.access(path, mode, callback)

Just like in accessSync(), here we also have to pass an additional parameter mode as “fs.constants.F_OK”  if we want to check the existence of a file.

Example:

const fs = require('fs');

const path = './example.txt';

fs.access(path, fs.constants.F_OK, (err) => {
  if (err) {
    console.log('File does not exist');
  } else {
    console.log('File exists');
  }
});

Output:

File exists

fs.readdir(path, callback)

This method is similar to readdirSync() which lists the contents of a directory and we can use the includes() method in callback to check for the existence of a specific file on it.

Example:

const fs = require('fs');

const path = './';

fs.readdir(path, (err, files) => {
  if (err) {
    console.log('Directory does not exist.');
  } else if (files.includes('example.txt')) {
    console.log('File exists');
  } else {
    console.log('File does not exist');
  }
});

Output:

File exists

Using async/await to Check File Exists

We can use async/await to wait for file to check if it exists using “fs.promises” API, which are promise-based versions of File System module methods.

Example:

const fs = require('fs');

async function isFileExists(filePath) {
  try {
    await fs.promises.access(filePath);
    console.log('File exists');
  } catch (err) {
    console.error('File does not exist');
  }
}

const filePath = './example.txt';
isFileExists(filePath);

Output:

File exists

Summary

This is a long tutorial, we learned several methods each one with different properties, if you just want to know if a file exists without much information, we recommend using the accessSync() method, which is the most efficient and easiest to implement. Hope you have enjoyed reading the rich content.

Check: Node.js Promises vs Async/Await

Reference

https://nodejs.org/api/fs.html

Aditya Gupta
Aditya Gupta
Articles: 109