Error: ENOENT no such file or directoryNode.js — Fixed [2026]
Also covers: Node.js readFile error · fs.readFileSync ENOENT · path resolution issues
⚡ Quickest Fix — Use __dirname
Replace relative paths with absolute paths using __dirname:
const path = require('path')
// ❌ WRONG — relative to wherever you run node from
fs.readFile('data/config.json', handler)
// ✅ CORRECT — absolute path from this file's location
fs.readFile(path.join(__dirname, 'data', 'config.json'), handler)What Does ENOENT Mean?
Error: ENOENT: no such file or directory, open 'config.json'
at Object.openSync (node:fs:600:3)
at Object.readFileSync (node:fs:468:35)
at Object.<anonymous> (/Users/you/projects/app/server.js:5:14)
# Or with readFile:
Error: ENOENT: no such file or directory, open '/Users/you/data.txt'ENOENT stands for Error NO ENTry — a Unix error code meaning the file or directory path does not exist. Node.js throws this whenever it tries to read, write, open, or access a path that cannot be found. The most common cause is a relative path that resolves incorrectly based on where you run node from.
Use __dirname for Absolute Paths
Most common fix — path resolutionIn Node.js, __dirname is the absolute path of the directory containing your current file. It never changes regardless of where you run node from. Use path.join(__dirname, ...) for all file paths.
const fs = require('fs')
const path = require('path')
// ❌ WRONG — relative to process.cwd() (where node is run from)
const config = fs.readFileSync('config.json', 'utf8')
// Fails if you run: node src/server.js from project root
// ✅ CORRECT — absolute path from this file's directory
const config = fs.readFileSync(
path.join(__dirname, 'config.json'), 'utf8'
)
// Always works regardless of where node is run from
// ✅ Navigating to parent directories
const pkg = fs.readFileSync(
path.join(__dirname, '..', 'package.json'), 'utf8'
)
// ✅ Building paths to subdirectories
const uploadPath = path.join(__dirname, 'uploads', 'images')path.join() handles OS differences automatically — it uses backslashes on Windows and forward slashes on macOS/Linux. Never concatenate paths with string operations like __dirname + '/file.txt'.
Understand process.cwd() vs __dirname
The root cause of most ENOENT errorsThese two are different and mixing them up causes most ENOENT errors:
| Variable | Value | Changes? |
|---|---|---|
| __dirname | Directory of the current .js file | Never |
| process.cwd() | Directory where you ran node | Yes — depends on terminal location |
// Project structure:
// /home/user/myapp/
// server.js
// src/utils.js
// config/settings.json
// In src/utils.js:
console.log(__dirname) // /home/user/myapp/src
console.log(process.cwd()) // /home/user/myapp (if run from myapp)
// // /home/user (if run from /home/user)
// Run from project root: node src/utils.js
// process.cwd() = /home/user/myapp → correct
// 'config/settings.json' → resolves to /home/user/myapp/config/settings.json ✅
// Run from /home/user: node myapp/src/utils.js
// process.cwd() = /home/user → WRONG
// 'config/settings.json' → resolves to /home/user/config/settings.json ❌ ENOENTVerify the File Actually Exists
Before debugging paths — confirm the file# macOS / Linux
ls -la /path/to/your/file.json
ls -la $(node -e "console.log(require('path').join(__dirname, 'config.json'))")
# Windows
dir C:\path\to\file.json
# In Node.js — check existence before reading
const fs = require('fs')
const path = require('path')
const filePath = path.join(__dirname, 'config.json')
if (!fs.existsSync(filePath)) {
console.error('File not found at:', filePath)
} else {
const content = fs.readFileSync(filePath, 'utf8')
}Print the full resolved path before reading: console.log('Reading:', path.join(__dirname, 'config.json')). This immediately shows you if the path is correct.
Fix readFile and readFileSync Errors
Complete fs patterns — sync and asyncAsync readFile — with error handling
const fs = require('fs')
const path = require('path')
// Callback style — always check err first
fs.readFile(path.join(__dirname, 'data.txt'), 'utf8', (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('File not found:', err.path)
} else {
console.error('Read error:', err.message)
}
return
}
console.log(data)
})
// Promise style (Node.js 10+)
const { readFile } = require('fs/promises')
async function readConfig() {
try {
const data = await readFile(path.join(__dirname, 'config.json'), 'utf8')
return JSON.parse(data)
} catch (err) {
if (err.code === 'ENOENT') {
console.error('Config file not found — using defaults')
return {} // return default config
}
throw err
}
}Sync readFileSync — with try/catch
// Always wrap in try/catch
let config = {}
try {
const raw = fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8')
config = JSON.parse(raw)
} catch (err) {
if (err.code === 'ENOENT') {
console.warn('config.json not found — using defaults')
} else {
throw err // re-throw unexpected errors
}
}readFileSync blocks the event loop while reading. For large files or high-traffic servers, use the async fs.promises.readFile() instead.
ENOENT in ES Modules — No __dirname
Using import/export — type: moduleES Modules do not have __dirname or __filename built in. Recreate them using import.meta.url.
import { readFile } from 'fs/promises'
import { fileURLToPath } from 'url'
import path from 'path'
// Recreate __filename and __dirname
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// Now use normally
const config = await readFile(
path.join(__dirname, 'config.json'), 'utf8'
)
// Or use import.meta.dirname (Node.js 21.2+)
// const config = await readFile(
// path.join(import.meta.dirname, 'config.json'), 'utf8'
// )ENOENT with fs.mkdir / fs.writeFile
Writing to directories that don't existENOENT on write operations means the directory you are writing to does not exist. Create it first.
const fs = require('fs/promises')
const path = require('path')
async function saveFile(filename, content) {
const dir = path.join(__dirname, 'uploads', 'images')
const filePath = path.join(dir, filename)
// Create directory if it doesn't exist
await fs.mkdir(dir, { recursive: true })
// recursive: true = create parent dirs too + no error if exists
// Now write the file
await fs.writeFile(filePath, content)
console.log('Saved to:', filePath)
}
// Sync version
fs.mkdirSync(path.join(__dirname, 'uploads'), { recursive: true }){ recursive: true } is the key option. It creates all parent directories in one call and does not throw if the directory already exists — safe to call every time.
ENOENT in Docker / Production
File exists locally but not on serverENOENT in production almost always means a file that exists locally was not deployed — either it is in .gitignore, or you need to create it at runtime.
- Check .gitignore — the file may be excluded from git and therefore not on the server
- Print the path at startup so you know exactly where Node is looking: console.log('Looking for:', path.join(__dirname, 'data.json'))
- In Docker — verify the file is COPY'd in Dockerfile: COPY data/ ./data/
- Create required directories at startup before reading files
- Use environment variables for file paths that differ between environments
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . . # copies all files including data/
# Ensure upload directory exists
RUN mkdir -p uploads/images
EXPOSE 3000
CMD ["node", "server.js"]Path Helpers — Quick Reference
const path = require('path')
// Join paths safely (handles / on any OS)
path.join(__dirname, 'data', 'file.txt')
// → /Users/you/app/data/file.txt
// Resolve to absolute path
path.resolve('relative/path')
// → /current/working/dir/relative/path
// Get directory of current file
__dirname
// → /Users/you/app/src
// Get file's basename
path.basename('/Users/you/app/src/server.js')
// → server.js
// Get file extension
path.extname('file.jpg')
// → .jpg
// Get directory from path
path.dirname('/Users/you/app/src/server.js')
// → /Users/you/app/srcHow to Prevent ENOENT Errors
- Always use path.join(__dirname, 'filename') — never bare relative paths
- Print resolved paths during debugging: console.log(path.join(__dirname, 'file.txt'))
- Check file existence with fs.existsSync() before reading
- Create directories with fs.mkdir(dir, { recursive: true }) before writing
- Recreate __dirname in ES modules with fileURLToPath(import.meta.url)
- In Docker: verify COPY commands include all required data files
- On servers: log paths at startup to confirm files are in expected locations
Frequently Asked Questions
What does ENOENT mean in Node.js?+−
What is the difference between __dirname and process.cwd()?+−
How do I fix readFile ENOENT?+−
ENOENT error only on production — why?+−
How do I create a directory if it does not exist in Node.js?+−
ENOENT with __dirname in ES modules?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds full-stack applications. Dealing with file system issues in production? We can help.
Talk to an Engineer