Skip to content
node

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

Nov 7, 2022Abhishek EH1 Min Read
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.

1const fs = require("fs")
2
3const exists = fs.existsSync("./reports/new.txt")
4
5if (exists) {
6 console.log("File exists")
7} else {
8 console.log("File does not exists")
9}

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.

1const fs = require("fs")
2
3fs.access("./reports/new.txt", fs.constants.F_OK, error => {
4 console.log({ error })
5 if (error) {
6 console.log(error)
7 return
8 }
9
10 console.log("File exists")
11})

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com