Table of Contents
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")23const exists = fs.existsSync("./reports/new.txt")45if (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")23fs.access("./reports/new.txt", fs.constants.F_OK, error => {4 console.log({ error })5 if (error) {6 console.log(error)7 return8 }910 console.log("File exists")11})
Do follow me on twitter where I post developer insights more often!
Leave a Comment