Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 and blocks the event loop. To check asynchronously, use fs.access(), which checks whether a file exists 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
})