Use fs.existsSync() or fs.access() to check file existence. They help prevent runtime errors before accessing a file.

Problem

When working with files in Node.js you often need to check if a file exists before reading, writing or deleting it, especially to avoid runtime errors.

Solution

Node.js provides both synchronous and asynchronous ways to check file existence using the fs module.

Using fs.existsSync (Synchronous)

js

const fs = require(‘fs’);if (fs.existsSync(‘path/to/file.txt’)) {

console.log(‘File exists’);

} else {

console.log(‘File does not exist’);

}

Note: This blocks the event loop. Use only in startup or script tasks.

Using fs.access (Asynchronous)

js

const fs = require(‘fs’);fs.access(‘path/to/file.txt’, fs.constants.F_OK, (err) => {

if (err) {

console.log(‘File does not exist’);

} else {

console.log(‘File exists’);

}

});

Also Read: How To Build A Node.js eCommerce Web Application?

Using fs.promises.access (With async/await)

js

const fs = require(‘fs’).promises;async function checkFile() {

try {

await fs.access(‘path/to/file.txt’);

console.log(‘File exists’);

} catch {

console.log(‘File does not exist’);

}

}

checkFile();

Conclusion

Always check if a file exists before performing operations on it. Use async methods in production to not block the event loop.