Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Cloud Services
AWS
Azure
Google Cloud
DevOps
Kubernetes
Salesforce
Microsoft
SAP
Front End
Back End
Mobile
Advanced Technologies
May 7, 2025
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
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();
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.
Read More