🔧 Error Fixes
· 1 min read

ENOENT: No Such File or Directory — How to Fix It


Error: ENOENT: no such file or directory, open '/app/config.json'
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

Your code is trying to read, write, or access a file or directory that doesn’t exist at the specified path.

Fix 1: Wrong File Path

// ❌ Relative path depends on where you run the script
fs.readFileSync('config.json');  // Looks in CWD, not script dir

// ✅ Use __dirname or import.meta
const path = require('path');
fs.readFileSync(path.join(__dirname, 'config.json'));

// ESM
const configPath = new URL('./config.json', import.meta.url);

Fix 2: File Doesn’t Exist Yet

// ❌ Reading a file that hasn't been created
const data = fs.readFileSync('output.json');

// ✅ Check if it exists first
if (fs.existsSync('output.json')) {
    const data = fs.readFileSync('output.json');
} else {
    fs.writeFileSync('output.json', '{}');
}

Fix 3: Missing Directory

// ❌ Writing to a directory that doesn't exist
fs.writeFileSync('logs/app.log', 'hello');  // 💥 If logs/ doesn't exist

// ✅ Create the directory first
fs.mkdirSync('logs', { recursive: true });
fs.writeFileSync('logs/app.log', 'hello');

Fix 4: npm/Node Modules Missing

# ENOENT during npm install or npm start
# ❌ node_modules is corrupted or missing

# ✅ Clean install
rm -rf node_modules package-lock.json
npm install

Fix 5: Docker — File Not Copied

# ❌ File exists locally but not in the container
COPY . .
# Did you forget to include it? Check .dockerignore

# ✅ Verify the file is in the build context
RUN ls -la /app/config.json

Fix 6: Environment-Specific Paths

// ❌ Hardcoded path that only works on your machine
const config = '/Users/john/project/config.json';

// ✅ Use environment variables or relative paths
const config = process.env.CONFIG_PATH || './config.json';

Debugging

# Check if the file exists
ls -la /path/to/file

# Check your current working directory
pwd

# Node.js — log the resolved path
console.log(path.resolve('config.json'));