In Node.js, checking whether a file exists is a common operation in file handling. This document explains different methods to check file existence using both synchronous and asynchronous approaches.
Before proceeding, ensure that you have Node.js installed on your system. You can verify this by running:
node -v
The fs.existsSync method is a simple way to check if a file exists synchronously.
Implementation:
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');
if (fs.existsSync(filePath)) {
console.log('File exists');
} else {
console.log('File does not exist');
}
Explanation:
The fs.promises.access method provides an asynchronous way to check file existence.
Implementation:
const fs = require('fs').promises;
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');
async function checkFile() {
try {
await fs.access(filePath);
console.log('File exists');
} catch (error) {
console.log('File does not exist');
}
}
checkFile();
Explanation:
| Method | Blocking | Recommended for |
| fs.existsSync | Yes | Simple, quick checks in scripts |
| fs.promises.access | No | Asynchronous applications |
Both synchronous and asynchronous methods are available to check if a file exists in Node.js. While fs.existsSync is straightforward, fs.promises.access is preferred for non-blocking operations.
Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js Developers