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
150
Related Errors
Frontend
React Key Warning
React warns that list items are missing unique "key" props for efficient rendering.
Frontend
Invalid DOM Property
The code uses an incorrect HTML attribute or React-specific prop on a DOM element.
ECONNREFUSED
Database
ECONNREFUSED
The network connection was refused by the target server.
ERR_MODULE_NOT_FOUND
Node.js
ERR_MODULE_NOT_FOUND
Node.js cannot find the specified ES module file.