Node.js Check If File Exists

Check if a file exists in Node.js using various fs module methods. Avoid runtime errors and handle missing files gracefully with async and sync checks.

Summarize with AI

Not enough time? get the key points instantly.

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’);

}

});

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();

Also Read: 

Conclusion

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


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…