How to Check if File Exists in Node.js: Simple Guide
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.
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.
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();
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.
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
| Method | Type | Description | Recommended Use |
|---|---|---|---|
| fs.promises.access(path, fs.constants.F_OK) | Async | Checks if file exists, returns promise | Best for modern async code |
| fs.existsSync(path) | Sync | Returns true/false if file exists | Use only for quick scripts or startup checks |
| fs.exists(path, callback) | Async (deprecated) | Checks if file exists with callback | Avoid, deprecated method |