Header Ads

ENOENT fix post

Getting “Error: ENOENT: no such file or directory” in Node.js, npm, Express or a deployment? This guide explains what it means and shows 7 fixes, from relative path mistakes and Linux letter case to missing files in Docker builds and “spawn ENOENT” on Windows.

Your app works on your laptop, then crashes on the server or in Docker with this message:

Error: ENOENT: no such file or directory, open '/app/data/config.json'
at Object.openSync (node:fs:603:3)
... {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/app/data/config.json'
}

ENOENT stands for “error, no entry”: the operating system looked for a file or folder at that path and found nothing. The useful details are the syscall (what Node tried to do, such as open, scandir or spawn) and the path (exactly where it looked).

Step 1: Read the Path and the Syscall

Look at the path in the error and ask three questions. Is it the path you expected? Does that file exist on this machine? Is it a file you wrote, or one that your build was supposed to create? Print what Node sees:

const fs = require('fs');
const path = require('path');

const target = path.join(__dirname, 'data', 'config.json');

console.log('cwd :', process.cwd());
console.log('__dirname:', __dirname);
console.log('target :', target);
console.log('exists? :', fs.existsSync(target));

The two values to compare are the current working directory (cwd) and the folder of your file (__dirname). Most ENOENT errors come from mixing them up.


Step 2: Do Not Use Paths Relative to the Working Directory

A path such as './data/config.json' is resolved against the folder from which you started the process, not against the folder that contains your code. It works when you run node server.js from the project root, and fails when PM2, Docker, a cron job or an IDE starts the app from another folder:

// fragile: depends on where you started Node
fs.readFileSync('./data/config.json', 'utf8');

// reliable in CommonJS: relative to this file
fs.readFileSync(path.join(__dirname, 'data', 'config.json'), 'utf8');

In ES modules, __dirname does not exist. Build it from import.meta.url:

import { fileURLToPath } from 'node:url';
import path from 'node:path';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const file = path.join(__dirname, 'data', 'config.json');

Newer Node.js versions also provide import.meta.dirname directly. Check that your Node version supports it before you rely on it.


Step 3: Check Letter Case on Linux

Windows and macOS usually ignore upper and lower case in file names. Linux does not. A file called Config.json will not be found with config.json on a Linux server:

// disk: Config.json
fs.readFileSync(path.join(__dirname, 'config.json')); // works on Windows, ENOENT on Linux

Rename the file or fix the path so the case matches exactly, and use one naming style in the whole project. If Git ignores a case-only rename on your computer, use git mv so the change reaches the server.


Step 4: Make Sure Your Build and Deploy Copy the File

The file may exist in your project but never reach the place where the app runs. Typical reasons:

  • TypeScript builds. tsc compiles .ts files into dist, but it does not copy JSON, HTML, templates or images. A path like path.join(__dirname, 'views/email.html') then points into dist where the file does not exist. Copy assets in your build script.
  • Docker. A .dockerignore entry or a missing COPY line can leave the file out of the image.
  • Git. The file is listed in .gitignore, so it never reaches the server. This is common for .env files and generated data.
{
"scripts": {
"build": "tsc && cp -r src/templates dist/templates"
}
}

The cp command works on macOS and Linux. For Windows or for one script that works everywhere, use a package such as copyfiles or cpy-cli. To see what Docker really contains, run docker run --rm -it your-image sh and look around with ls.


Step 5: Create Folders Before You Write Files

Writing a file into a folder that does not exist also gives ENOENT, because Node does not create missing folders for you:

const fs = require('fs/promises');
const path = require('path');

async function saveReport(name, content) {
const dir = path.join(__dirname, 'reports');
await fs.mkdir(dir, { recursive: true }); // creates the folder if needed
await fs.writeFile(path.join(dir, name), content);
}

The recursive: true option also makes the call safe when the folder already exists. For uploads, logs and exports on a fresh server, this one line prevents many first-run crashes.


Step 6: Fix “spawn ENOENT” (Running Commands)

If the error says spawn something ENOENT, Node could not find the program you asked it to run, not a data file:

Error: spawn npm ENOENT
Error: spawn git ENOENT
  • The program is not installed, or its folder is not on the PATH of the process that runs your app.
  • On Windows, commands such as npm are really npm.cmd files, and child_process.spawn cannot find them without help. Use shell: true or the .cmd name.
  • The cwd option you passed to spawn points to a folder that does not exist. That also produces spawn ... ENOENT.
const { spawn } = require('child_process');

// Windows-friendly
const child = spawn('npm', ['run', 'build'], { shell: true, cwd: projectDir });

Use shell: true only with fixed commands that you wrote yourself. Never pass user input into a shell command, because that opens the door to command injection.


Step 7: Fix npm’s ENOENT for package.json

When npm itself says it cannot find a file, the cause is almost always the folder you are in:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /home/you/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/home/you/package.json'

Run pwd (or cd on Windows) and make sure you are in the folder that contains package.json. If you are, check that the file was not deleted by a failed install or a bad Git checkout. A related error, uv_cwd, appears when the folder you are standing in was deleted, so move to an existing folder with cd ~ and come back.


Quick Diagnosis Table

What you seeLikely causeGo to
Works with node server.js, fails under PM2, Docker or cronRelative path depends on the working directoryStep 2
Works on Windows or macOS, fails on LinuxLetter case in the file nameStep 3
Works in development, fails after npm run buildBuild did not copy the fileStep 4
Fails when writing into a folderFolder does not existStep 5
spawn xyz ENOENTProgram not found, or Windows .cmd issueStep 6
npm ERR! enoent ... package.jsonWrong folderStep 7


Debug Checklist

  1. Copy the path and syscall from the error.
  2. Print process.cwd(), __dirname and fs.existsSync(path).
  3. Replace relative paths with path.join(__dirname, ...).
  4. Compare the exact file name and letter case on the server.
  5. Check that your build, Docker image and Git repository really contain the file.
  6. For spawn errors, run the same command in the same terminal and folder.


Conclusion

ENOENT is Node.js telling you the exact path it could not find. Compare that path with the real files on this machine, build paths from __dirname, match letter case, make sure your build and Docker image include the file, and create folders before you write into them. Once you print the working directory and the full path, the cause is usually obvious.

Related Guides

Post a Comment

0 Comments