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 and will block the execution until the operation is completed.

fs.access() Method

If you want to check if the file exists asynchronously, use the fs.access() method instead. It is the non-blocking way of checking the file's 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:

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

In addition to checking the file's existence, you can even use the 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.