0
0
NodejsHow-ToBeginner · 3 min read

How to Check if File Exists in Node.js: Simple Guide

In Node.js, you can check if a file exists by using the fs.access() method from the fs/promises module with async/await for modern code. Alternatively, fs.existsSync() provides a synchronous check but is less recommended for non-blocking code.
📐

Syntax

The modern way to check if a file exists is using fs.access(path, fs.constants.F_OK). This checks if the file is visible to the process. Using fs/promises with async/await makes the code clean and non-blocking.

  • path: The file path to check.
  • fs.constants.F_OK: Flag to test file existence.
  • Returns a promise that resolves if the file exists, rejects if not.

For synchronous checks, fs.existsSync(path) returns true or false immediately but blocks the event loop.

javascript
import { access, constants } from 'fs/promises';
import { existsSync } from 'fs';

// Async check
await access(path, constants.F_OK);

// Sync check
const exists = existsSync(path);
💻

Example

This example shows how to check if a file named example.txt exists asynchronously using fs/promises. It prints a message based on the result.

javascript
import { access, constants } from 'fs/promises';

async function checkFile() {
  const filePath = './example.txt';
  try {
    await access(filePath, constants.F_OK);
    console.log('File exists');
  } catch {
    console.log('File does not exist');
  }
}

checkFile();
Output
File exists
⚠️

Common Pitfalls

A common mistake is using fs.exists(), which is deprecated and should be avoided. Another is using synchronous methods like fs.existsSync() in performance-critical or server code, which blocks the event loop and slows down your app.

Also, checking file existence and then opening the file separately can cause race conditions if the file changes between checks. It's better to handle errors when opening the file directly.

javascript
import { existsSync } from 'fs';

// Less recommended synchronous check (blocks event loop)
if (existsSync('./file.txt')) {
  console.log('File exists');
} else {
  console.log('File does not exist');
}

// Avoid deprecated fs.exists
// fs.exists('./file.txt', (exists) => { ... }); // Don't use
📊

Quick Reference

MethodTypeDescriptionRecommended Use
fs.promises.access(path, fs.constants.F_OK)AsyncChecks if file exists, returns promiseBest for modern async code
fs.existsSync(path)SyncReturns true/false if file existsUse only for quick scripts or startup checks
fs.exists(path, callback)Async (deprecated)Checks if file exists with callbackAvoid, deprecated method

Key Takeaways

Use fs.promises.access with async/await for non-blocking file existence checks.
Avoid deprecated fs.exists and synchronous fs.existsSync in performance-sensitive code.
Handle file open errors instead of separate existence checks to avoid race conditions.
Synchronous checks block the event loop and should be limited to simple scripts.
Always prefer modern promise-based APIs in Node.js for cleaner and safer code.