How to check if a file exists in Node.js

How to use Node.js to check if a file exists in the file system using the following commandfsModule

The way to use Node.js to check if a file exists in the file system is to usefs.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 it is blocking. To check if the file exists asynchronously, you can usefs.access(), It will check the existence of the file without opening the file:

const fs = require('fs')

const path = ‘./file.txt’

fs.access(path, fs.F_OK, (err) => { if (err) { console.error(err) return }

//file exists })

Download mine for freeNode.js manual


More node tutorials: