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
})
Download my free Node.js Handbook and check out my Node.js Course!
More node tutorials:
- Understanding process.nextTick()
- Where to host a Node.js app
- How to read a CSV file with Node.js
- How to exit from a Node.js program
- How to spawn a child process with Node.js
- Get the current folder in Node
- HTTP requests in Node using Axios
- How to create an empty file in Node.js
- The Node path module