How to check if a file exists in Node.js
Checking file existence is essential for preventing errors, validating inputs, and implementing conditional file operations in Node.js applications and scripts.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file existence checks in numerous Node.js build tools, deployment scripts, and file processing utilities for CoreUI projects.
From my expertise, the most modern approach is to use fs.promises.access()
for asynchronous operations.
This method provides proper error handling, non-blocking behavior, and integrates well with async/await patterns for clean, maintainable code.
Use fs.promises.access()
for asynchronous file existence checks with proper error handling.
const fs = require('fs').promises
const path = require('path')
async function fileExists(filePath) {
try {
await fs.access(filePath, fs.constants.F_OK)
return true
} catch (error) {
return false
}
}
// Usage examples
async function processFile() {
const configPath = './config.json'
if (await fileExists(configPath)) {
console.log('Config file exists, loading...')
const config = JSON.parse(await fs.readFile(configPath, 'utf8'))
return config
} else {
console.log('Config file not found, using defaults')
return { default: true }
}
}
// For synchronous operations (use sparingly)
function fileExistsSync(filePath) {
try {
require('fs').accessSync(filePath, require('fs').constants.F_OK)
return true
} catch (error) {
return false
}
}
The fs.promises.access()
method checks if a file exists and is accessible with the specified permissions. Use fs.constants.F_OK
to check existence, fs.constants.R_OK
for read access, or fs.constants.W_OK
for write access. The method throws an error if the file doesn’t exist or lacks permissions, which you can catch to determine file status. This approach is non-blocking and works well with modern async/await patterns for better application performance.
Best Practice Note:
This is the same approach we use in CoreUI build processes for conditional file operations and validation.
Avoid the deprecated fs.exists()
method, use fs.promises.access()
for async operations and fs.accessSync()
only when synchronous behavior is required during application startup or CLI tools.