Error Encyclopedia

ENOENT: File Not Found Error

Fix 'ENOENT: no such file or directory' errors in Node.js. Learn how to check file paths, handle missing files gracefully, and debug file system operations.

What Does This Error Mean?

The ENOENT (Error NO ENTity) error means Node.js tried to access a file or directory that does not exist at the specified path. This is one of the most common Node.js errors and usually indicates a wrong file path or missing file.

Common Causes

1

Relative file path is incorrect for the current working directory

2

File was deleted or moved after the application started

3

Missing configuration or environment file

4

Directory does not exist when trying to create a file inside it

5

File permission issues that make the file invisible

6

Symbolic link pointing to a non-existent target

How to Fix It

Use absolute paths with __dirname

Avoid relative paths that depend on the current working directory.

const fs = require("fs")
const path = require("path")

// ❌ Relative path depends on cwd
fs.readFileSync("config.json")

// ✅ Absolute path using __dirname (current file directory)
fs.readFileSync(path.join(__dirname, "config.json"))

// ✅ Or use process.cwd() for project root
fs.readFileSync(path.join(process.cwd(), "config.json"))

Check if file exists before reading

Use fs.existsSync() or try-catch to handle missing files gracefully.

const fs = require("fs")

// Check existence
if (fs.existsSync("config.json")) {
  const data = fs.readFileSync("config.json", "utf-8")
} else {
  console.warn("Config file not found, using defaults")
  const data = "{}"
}

// Or try-catch
let config
const config = JSON.parse(fs.readFileSync("config.json", "utf-8"))

Create missing directories

Ensure parent directories exist before writing files.

const fs = require("fs")
const path = require("path")

function writeFileSafe(filePath, data) {
  const dir = path.dirname(filePath)
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true }) // Creates all parent dirs
  }
  fs.writeFileSync(filePath, data)
}

Before & After Examples

❌ Before
// ❌ Assumes file is in cwd
const data = fs.readFileSync("data/users.json", "utf-8")
✅ After
// ✅ Uses correct path relative to script location
const data = fs.readFileSync(
  path.join(__dirname, "..", "data", "users.json"),
  "utf-8"
)

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: