Node.jsFile SystemError Fix2026 Updated

Error: ENOENT no such file or directoryNode.js — Fixed [2026]

Also covers: Node.js readFile error · fs.readFileSync ENOENT · path resolution issues

January 20266 min readNode.js · All OS

⚡ Quickest Fix — Use __dirname

Replace relative paths with absolute paths using __dirname:

server.js
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?

Terminal Error
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.

1

Use __dirname for Absolute Paths

Most common fix — path resolution
2 min

In 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.

server.js
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'.

2

Understand process.cwd() vs __dirname

The root cause of most ENOENT errors
2 min

These two are different and mixing them up causes most ENOENT errors:

VariableValueChanges?
__dirnameDirectory of the current .js fileNever
process.cwd()Directory where you ran nodeYes — depends on terminal location
Practical example
// 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 ❌ ENOENT
3

Verify the File Actually Exists

Before debugging paths — confirm the file
1 min
terminal
# 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.

4

Fix readFile and readFileSync Errors

Complete fs patterns — sync and async
3 min

Async readFile — with error handling

server.js
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

server.js
// 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.

5

ENOENT in ES Modules — No __dirname

Using import/export — type: module
2 min

ES Modules do not have __dirname or __filename built in. Recreate them using import.meta.url.

server.js (ES Module)
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'
// )
6

ENOENT with fs.mkdir / fs.writeFile

Writing to directories that don't exist
2 min

ENOENT on write operations means the directory you are writing to does not exist. Create it first.

server.js
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.

7

ENOENT in Docker / Production

File exists locally but not on server
3 min

ENOENT 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
Dockerfile
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/src

How to Prevent ENOENT Errors

Frequently Asked Questions

What does ENOENT mean in Node.js?+
ENOENT stands for 'Error NO ENTry' — the file or directory path you provided does not exist. Either the path is wrong, the file has not been created yet, or you are running Node from a different directory than expected.
What is the difference between __dirname and process.cwd()?+
__dirname is the directory of the current JavaScript file — it never changes regardless of where you run node from. process.cwd() is the directory where you ran the node command — it changes if you run node from a different folder. Use __dirname for file paths.
How do I fix readFile ENOENT?+
Use path.join(__dirname, 'filename.txt') instead of a bare filename. Bare filenames are resolved relative to process.cwd() (where you ran node), not your file's location. __dirname gives you an absolute path that always works.
ENOENT error only on production — why?+
Your file exists locally but not on the server. The file may be in .gitignore, the directory structure may differ, or the file needs to be created at runtime. Check that all required files are committed and your deploy process creates any needed directories.
How do I create a directory if it does not exist in Node.js?+
Use fs.mkdirSync(dirPath, { recursive: true }) or await fs.promises.mkdir(dirPath, { recursive: true }). The recursive: true option creates parent directories too and does not throw if the directory already exists.
ENOENT with __dirname in ES modules?+
__dirname does not exist in ES modules. Use: import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename). Then use __dirname as normal.

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