How to check if a file exists in Node.js
How to check if a file exists in the filesystem using Node.js, using the `fs` module
The way to check if a file exists in the filesystem, using Node.js, is by using the fs.existsSync()
method:
const fs = require('fs')
const path = './file.txt'
try {
if (fs.existsSync(path)) {
//file exists
}
} catch(err) {
console.error(err)
}
This method is synchronous. This means that it’s blocking. To check if a file exists in an asynchronous way, you can use fs.access()
, which checks the existence of a file without opening it:
const fs = require('fs')
const path = './file.txt'
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err)
return
}
//file exists
})
→ Get my Node.js Handbook
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025