DEV Community

Cover image for How to check if a file exists in Node.js?
collegewap
collegewap

Posted on • Originally published at codingdeft.com

How to check if a file exists in Node.js?

Mainly there are 2 ways in which we can check if a file exists.
We will be using the fs API provided out of the box by Node.js

Synchronous way

We can use the existsSync method to check if a particular file exists.

const fs = require("fs")

const exists = fs.existsSync("./reports/new.txt")

if (exists) {
  console.log("File exists")
} else {
  console.log("File does not exists")
}
Enter fullscreen mode Exit fullscreen mode

existsSync is a synchronous call and will block all the requests till the function returns control.

Asynchronous way

If you want to check if a file exists asynchronously,
you can use the access method.

const fs = require("fs")

fs.access("./reports/new.txt", fs.constants.F_OK, error => {
  console.log({ error })
  if (error) {
    console.log(error)
    return
  }

  console.log("File exists")
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)