Real-world examples of file not found error examples in Node.js
The most common examples of file not found error examples in Node.js
Let’s start where the pain is real: actual failures developers hit every day. These are the best examples because they’re boringly common and surprisingly easy to repeat.
Node’s file not found errors usually look like this:
Error: ENOENT: no such file or directory, open 'config.json'
Error: ENOENT: no such file or directory, scandir './uploads'
Error: ENOENT: no such file or directory, stat '/var/app/public/logo.png'
Under the hood, these all map to the same thing: Node asked the operating system to read a path, and the OS said, “Nope, nothing there.”
Below are several real examples of file not found error examples in Node.js, each with a short story, the code, and the fix.
Example of a missing config file in the wrong working directory
You run:
node src/server.js
Inside server.js:
const fs = require('fs');
const config = JSON.parse(
fs.readFileSync('config.json', 'utf8')
);
Locally, from the project root, it works. On CI or in production, you suddenly get:
Error: ENOENT: no such file or directory, open 'config.json'
The bug: fs.readFileSync('config.json') is using the current working directory, not the file’s directory. When you run Node from a different folder, Node looks for config.json in the wrong place.
The fix is to anchor the path to the script’s directory:
const path = require('path');
const fs = require('fs');
const configPath = path.join(__dirname, '..', 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
This is one of the most frequent examples of file not found error examples in Node.js because people confuse process.cwd() with __dirname. In 2024–2025, with more teams using monorepos and complex build scripts, this mismatch shows up even more.
Real examples of file not found error examples in Node.js with static assets in Express
Express apps love to serve static files. They also love to break when you move things.
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static('public'));
app.listen(3000);
This works fine when you run from the project root and you have ./public/logo.png. Then you containerize the app, change the working directory, or move the public folder, and suddenly users see 404s while your logs quietly show:
Error: ENOENT: no such file or directory, stat '/usr/src/app/public/logo.png'
The Express static middleware is just calling fs.stat under the hood. The path 'public' is again relative to the working directory.
Safer version:
app.use(
'/static',
express.static(path.join(__dirname, 'public'))
);
This is a textbook example of file not found error examples in Node.js web apps: everything works on the laptop, then breaks the moment the app runs from a different directory in Docker or a cloud platform.
When build tools move files: Next.js, bundlers, and missing runtime files
Modern Node projects often have a build step. You might generate files into .next, dist, or build. A classic trap is reading a file that only exists before the build.
For instance, in a Next.js app, you might write:
// pages/api/data.js
import fs from 'fs';
export default function handler(req, res) {
const raw = fs.readFileSync('./data/users.json', 'utf8');
res.status(200).json(JSON.parse(raw));
}
Locally, ./data/users.json is there. In production, depending on how you deploy, the data folder might not be copied into the final image or output directory. The runtime then throws:
Error: ENOENT: no such file or directory, open './data/users.json'
Better approach:
- Store data in a real database or a persistent store.
- If you must keep JSON files, ensure they are included in the build artifact and use
__dirname-based paths.
This is one of the more modern examples of file not found error examples in Node.js, driven by the rise of frameworks that separate build-time and runtime environments.
Examples include missing upload directories in file APIs
File uploads are another classic source of ENOENT. Imagine a simple upload endpoint:
const fs = require('fs');
const path = require('path');
function saveUpload(filename, content) {
const uploadDir = path.join(__dirname, 'uploads');
const filePath = path.join(uploadDir, filename);
fs.writeFileSync(filePath, content);
}
This looks fine, but in a fresh environment there is no uploads folder. Node then fails with:
Error: ENOENT: no such file or directory, open '/app/uploads/photo.png'
The directory doesn’t exist, so the file cannot be created.
Safer pattern:
const fs = require('fs');
const path = require('path');
function ensureDirSync(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function saveUpload(filename, content) {
const uploadDir = path.join(__dirname, 'uploads');
ensureDirSync(uploadDir);
const filePath = path.join(uploadDir, filename);
fs.writeFileSync(filePath, content);
}
In 2024–2025, with more apps running in ephemeral containers or serverless functions, you need to be explicit about creating directories and understanding which paths are actually writable. This is a very real example of file not found error examples in Node.js APIs that appears during the first staging deployment.
A subtle example of file not found error examples in Node.js tests
Testing environments often change the working directory or run from a different root. Suppose you have:
// src/loadTemplate.js
const fs = require('fs');
module.exports = function loadTemplate(name) {
return fs.readFileSync(`templates/${name}.html`, 'utf8');
};
Your Jest test:
// tests/loadTemplate.test.js
const loadTemplate = require('../src/loadTemplate');
test('loads welcome template', () => {
const html = loadTemplate('welcome');
expect(html).toContain('Welcome');
});
On your machine, this passes. In CI, you suddenly see:
Error: ENOENT: no such file or directory, open 'templates/welcome.html'
Jest may be running tests from a different root or using a different cwd. Again, the fix is to base paths on __dirname:
const path = require('path');
const fs = require('fs');
module.exports = function loadTemplate(name) {
const templatePath = path.join(__dirname, '..', 'templates', `${name}.html`);
return fs.readFileSync(templatePath, 'utf8');
};
This is one of the best examples of file not found error examples in Node.js because it highlights how tests and production can disagree about file locations even when the code is identical.
Docker and deployment: paths that work locally but not in containers
Now for a production-flavored case.
Locally, your project structure looks like:
project/
src/
server.js
public/
index.html
server.js:
const path = require('path');
const fs = require('fs');
const indexHtml = fs.readFileSync(
path.join(__dirname, '..', 'public', 'index.html'),
'utf8'
);
Then you write a Dockerfile:
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY src ./src
CMD ["node", "src/server.js"]
You forgot to copy public. The container starts and immediately throws:
Error: ENOENT: no such file or directory, open '/usr/src/app/public/index.html'
The fix is obvious once you see it:
COPY public ./public
But this is still one of the most common real examples of file not found error examples in Node.js production deployments. The file literally doesn’t exist in the image, even though it exists in your repo.
Case sensitivity: works on macOS, fails on Linux
macOS and Windows are often case-insensitive for file names; Linux is not. That difference creates a sneaky class of file not found errors.
Suppose your file is named Config.json but your code says:
const config = require('./config.json');
On macOS, this might still work. On a Linux server (or Docker image based on Linux), you’ll get:
Error: Cannot find module './config.json'
at Module._resolveFilename ...
Or with fs:
Error: ENOENT: no such file or directory, open '/app/config.json'
This is another example of file not found error examples in Node.js that shows up only after deployment. The fix: treat file names like you treat variable names—case matters. And if you’re using Git, make sure case-only renames are handled properly.
How to systematically debug file not found errors in Node.js
At this point, you’ve seen several real examples of file not found error examples in Node.js. They all share a few themes:
- Confusion between
__dirnameandprocess.cwd() - Files or folders missing from the runtime environment
- Paths that change between local, CI, and production
- Case sensitivity differences
When you hit an ENOENT, don’t guess. Instrument it.
Add logging around the path you’re using:
const path = require('path');
const fs = require('fs');
function safeRead(p) {
console.log('Attempting to read:', p);
console.log('Exists?', fs.existsSync(p));
console.log('CWD:', process.cwd());
console.log('__dirname:', __dirname);
return fs.readFileSync(p, 'utf8');
}
Run the code and see exactly which path Node is touching and whether it exists.
For more background on how operating systems expose file errors and why you see ENOENT, the POSIX standard is still the reference point. The Open Group publishes detailed descriptions of error codes and file operations at:
- https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html
Even though it isn’t Node-specific, it explains where ENOENT comes from and why it behaves consistently across Unix-like systems.
FAQs about file not found error examples in Node.js
Q: What are some common examples of file not found error examples in Node.js?
Common examples include missing config files when the working directory changes, static assets not copied into Docker images, upload directories that were never created, test environments using a different root path, and case mismatches between file names and import paths on Linux.
Q: Can you give an example of a file not found error caused by require instead of fs?
Yes. If you write require('./config.json') but the file is actually named Config.json, it may work on macOS but fail on Linux with Cannot find module './config.json'. That is effectively a file not found error, triggered by Node’s module resolution instead of fs.readFile.
Q: How do I avoid these errors when deploying to Docker or cloud platforms?
Be explicit about what you copy into the image or artifact. Use __dirname-based paths, verify that all needed files are included in your Dockerfile or build output, and log the resolved paths when something fails. Running your app in a local container that mirrors production is often the fastest way to catch these problems early.
Q: Are ENOENT errors always fatal?
Not necessarily. For optional files (like a user-provided config override), you can catch the error and fall back to defaults:
try {
const override = fs.readFileSync(overridePath, 'utf8');
// use override
} catch (err) {
if (err.code === 'ENOENT') {
// fall back to defaults
} else {
throw err;
}
}
The key is to be intentional. If a file is required for the app to function, fail fast and loudly; if it’s optional, handle ENOENT explicitly.
Q: Where can I learn more about Node.js file system behavior?
The official Node.js documentation is still the best starting point for accurate, up-to-date behavior:
- Node.js
fsmodule: https://nodejs.org/api/fs.html - Node.js path handling: https://nodejs.org/api/path.html
These docs are maintained by the Node.js project and updated for new releases, including current LTS versions used heavily in 2024–2025.
If you remember nothing else from these examples of file not found error examples in Node.js, remember this: always know which directory your code thinks it’s in, and never assume a file exists just because it does on your laptop.
Related Topics
Real-world examples of file not found error examples in Node.js
Practical examples of file not found error examples in Java (and how to fix them)
The best examples of file not found error examples in HTML linking (and how to fix them)
Real-world examples of resolving file not found error in Linux
Modern examples of File Not Found exception handling in real code
Examples of File Not Found Error in Python: 3 Practical Examples (Plus More You Actually See)
Explore More File Not Found Errors
Discover more examples and insights in this category.
View All File Not Found Errors