ENOENT: No Such File or Directory
The operating system cannot find the specified file or directory.
Explanation
ENOENT (Error NO ENTry or Error NO ENTitly) is an OS-level error indicating that a file or directory does not exist at the specified path. In Node.js, this typically occurs when using the fs module to read, write, or access files. Unlike JavaScript ReferenceErrors, this is a system error from the operating system. Common causes include incorrect file paths, files not yet created, deleted files, wrong working directory, or case sensitivity issues on Linux.
Common Causes
- File path doesn't exist
- File was deleted or moved
- Wrong working directory
- File path typo
- Case sensitivity on Linux
Solution
Verify the file path exists using fs.existsSync() or fs.promises.access(). Use path.join() or path.resolve() to construct paths portably. Check the working directory with process.cwd(). Ensure all file operations happen after the file is created (use async/await or callbacks). Use __dirname in CommonJS or import.meta.url in ES modules for reliable directory references. Check case sensitivity on Linux. Create parent directories with fs.mkdirSync(path, { recursive: true }).
Code Example
// ENOENT when reading non-existent file
const fs = require('fs');
fs.readFile('data.json', 'utf8', (err, data) => {
if (err.code === 'ENOENT') {
console.log('File not found');
}
});
// Fix: check existence first
const path = require('path');
const filePath = path.join(__dirname, 'data.json');
if (fs.existsSync(filePath)) {
const data = fs.readFileSync(filePath, 'utf8');
}
// Use async/await with proper error handling
const fsPromises = require('fs').promises;
async function readFile() {
try {
const data = await fsPromises.readFile(filePath, 'utf8');
return data;
} catch (err) {
if (err.code === 'ENOENT') {
return null; // file doesn't exist
}
throw err; // other error
}
}
// Ensure directory exists before writing
await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
await fsPromises.writeFile(filePath, data);
Error Information
Language
javascript
Framework
nodejs
Difficulty
Beginner
Views
14
Related Errors
ERESOLVE
JavaScript
npm ERESOLVE Unable to Resolve Dependency Tree
npm cannot install a package due to conflicting dependency requirements.
ENOTFOUND
DevOps
Node.js ENOTFOUND
DNS lookup failed because the hostname could not be resolved.
Frontend
Content Security Policy Violation
The browser blocked a resource because it violated the Content Security Policy.
Frontend
Invalid CSS Property
The code sets a CSS property that doesn't exist or uses incorrect syntax.