DEV Community

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

Posted on • Originally published at codingdeft.com

4

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay