Fixing ENOENT When Reading Files in Node.js
When readFileSync or readFile in Node.js throws Error: ENOENT: no such file or directory, open './config.json', the file is not where Node.js looked for it. A relative path like ./config.json is resolved from the folder where you ran the command, not from the folder where the script is. If you change the path to one based on the script's location (for example, new URL('./config.json', import.meta.url)), the error goes away no matter where you run the script from.
This is the fix for a script that reads a config file, JSON data, or a template kept in the same folder as the script, and then stops with "file not found" when you run it from another folder or through npm run. I reproduced this error in my test environment and included the output as it appeared. I also confirmed that the error disappears after the fix.
The test environment was Ubuntu 24.04. I mainly used Node.js 24.22.3 (npm 11.19.1) and also ran the code on Node.js 22.23.5 for comparison. I did not test Windows or macOS, running TypeScript files directly, or ENOENT from operations other than reading, such as writing or fs.stat. In the output shown in this article, I replaced the working directory in my test environment with /path/to/app. The ENOENT that npm prints when it cannot find package.json (npm error code ENOENT) is not covered here.
The Full Error
For testing, I made the following folder layout. Inside scripts/ there is a config.json that contains only {"title":"hello"}, and show-config.mjs, which reads it.
app/
└── scripts/
├── config.json
└── show-config.mjs
// Read config.json in the same folder as this script and print it
import { readFileSync } from 'node:fs';
const text = readFileSync('./config.json', 'utf8');
console.log(JSON.parse(text).title);
When I moved into scripts/ and ran node show-config.mjs, it printed hello. However, when I ran node scripts/show-config.mjs from app/, one level up, it stopped with the following output (exit code 1).
$ node scripts/show-config.mjs
node:fs:483
return binding.readFileUtf8(path, stringToFlags(options.flag));
^
Error: ENOENT: no such file or directory, open './config.json'
at readFileSync (node:fs:483:20)
at file:///path/to/app/scripts/show-config.mjs:4:14
at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
at async node:internal/modules/esm/loader:647:26
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: './config.json'
}
Node.js v24.22.3
On Node.js 22.23.5, the Error: ENOENT line and everything from errno down to path were the same. What differed were the lines pointing into Node.js internals (line numbers such as node:fs:440, and function names such as at async onImport.tracePromise.__proto__), and the version on the last line.
When I used readFile from fs/promises with await, the first three lines that show where the error occurred, and the stack trace, were different. On Node.js 24.22.3, the output was as follows.
$ node scripts/show-config-promises.mjs
node:internal/fs/promises:1345
return new FileHandle(await PromisePrototypeThen(
^
Error: ENOENT: no such file or directory, open './config.json'
at async open (node:internal/fs/promises:1345:25)
at async readFile (node:internal/fs/promises:2003:14)
at async file:///path/to/app/scripts/show-config-promises.mjs:4:14 {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: './config.json'
}
Node.js v24.22.3
Reading the Message
syscall: 'open' means the failure happened when trying to open the file. code: 'ENOENT' means that the file or folder does not exist (errno: -2 is the corresponding number). The list of common system errors in the official Node.js documentation describes it as "no such file or directory" at the specified path.
The parts to check are the path value and the file:///… line in the stack trace. file:///…/show-config.mjs:4:14 means the error occurred on line 4 of show-config.mjs. path shows the string exactly as it was written in the code. When it is a relative path like ./config.json, check what base directory was used for the lookup, as described in the next section.
Relative Paths Are Resolved from the Directory Where You Ran the Command
The Node.js fs documentation states that a relative path passed as a string is resolved against process.cwd(), the folder you were in when you ran the command. Where the script file lives does not matter.
You can confirm exactly where the path points with the following script. It converts the relative path to an absolute one with path.resolve() and uses existsSync() to show whether a file exists there.
// Show where a relative path points
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
console.log('cwd: ', process.cwd());
console.log('resolved:', resolve('./config.json'));
console.log('exists: ', existsSync('./config.json'));
I saved this as scripts/where.mjs and ran it from app/ and from scripts/. These are the results.
$ node scripts/where.mjs
cwd: /path/to/app
resolved: /path/to/app/config.json
exists: false
$ cd scripts && node where.mjs
cwd: /path/to/app/scripts
resolved: /path/to/app/scripts/config.json
exists: true
When I ran it from app/, it was looking for app/config.json. Nothing was there, so it gave ENOENT.
The Same Thing Happens with npm run
I added "show": "node scripts/show-config.mjs" to the scripts field in package.json, then ran npm run show from inside scripts/. It still stopped with the same ENOENT. The message was the same as in the full output above.
$ cd scripts && npm run show
> show
> node scripts/show-config.mjs
node:fs:483
The lines after node:fs:483 are the same as in the full output above, so I have omitted them.
The npm documentation has a section on the directory where scripts run. It says that scripts run from the package root (the folder containing package.json), regardless of the folder where npm was invoked. I added "where": "node scripts/where.mjs" to package.json and ran npm run where from inside scripts/. The cwd: line showed /path/to/app. Even when run from scripts/, ./config.json points to app/config.json.
The Fix: Base the Path on the Script's Location
If the file you want to read is in the same folder as the script, use the script file's location as the base, not process.cwd(). In ES modules (.mjs, or a .js file in a package with "type": "module" in package.json), import.meta.url is available.
// Read config.json in the same folder as this script and print it
import { readFileSync } from 'node:fs';
const text = readFileSync(new URL('./config.json', import.meta.url), 'utf8');
console.log(JSON.parse(text).title);
import.meta.url is the file: URL of the module's file. new URL('./config.json', import.meta.url) produces a URL pointing to the config.json next to the script, and it can be passed to readFileSync as is. The Node.js ES modules documentation also shows this pattern as an example.
After the change, the script printed hello from every location I tried, and ENOENT no longer appeared.
$ node scripts/show-config.mjs
hello
$ cd scripts && node show-config.mjs
hello
$ cd / && node /path/to/app/scripts/show-config.mjs
hello
$ cd scripts && npm run show
> show
> node scripts/show-config.mjs
hello
On Node.js 22.23.5, running it from app/ also printed hello.
Using import.meta.dirname or __dirname
If you prefer to build a plain path string instead of a URL, use import.meta.dirname (the absolute path of the folder containing the script) together with path.join(). According to the Node.js documentation for import.meta.dirname, it was added in Node.js 20.11.0 and 21.2.0.
// Use import.meta.dirname (the folder containing this script) as the base
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const text = readFileSync(join(import.meta.dirname, 'config.json'), 'utf8');
console.log(JSON.parse(text).title);
For CommonJS files (those that use require, such as .cjs), use __dirname, which plays the same role.
// In CommonJS, use __dirname (the folder containing this script) as the base
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const text = readFileSync(join(__dirname, 'config.json'), 'utf8');
console.log(JSON.parse(text).title);
Both printed hello when run from app/ and when run by absolute path after cd /. The import.meta.dirname version also worked on Node.js 22.23.5. In ES module files __dirname is not available, so use import.meta.dirname there.
If the Path Looks Right but You Still Get the Error, Check the Case of the Name
Even after switching to a script-relative path, ENOENT can still occur if the file name itself is wrong. On my test environment (Linux), file names are case-sensitive. scripts/ had config.json but no Config.json, and when the code used Config.json, I got this:
$ node scripts/show-config-case.mjs
node:fs:483
return binding.readFileUtf8(path, stringToFlags(options.flag));
^
Error: ENOENT: no such file or directory, open '/path/to/app/scripts/Config.json'
at readFileSync (node:fs:483:20)
at file:///path/to/app/scripts/show-config-case.mjs:5:14
at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
at async node:internal/modules/esm/loader:647:26
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/path/to/app/scripts/Config.json'
}
Node.js v24.22.3
Because the path is built as an absolute path, path also shows an absolute path. Compare the path shown here with the actual file name from ls character by character, and the difference will become visible. After I changed Config.json to config.json in the code, it printed hello.
For Files That May Not Exist, Handle Only ENOENT
For a config file that the user may or may not have created, a missing file is acceptable, so you can catch the error and continue with default values. In that case, do not swallow every error in catch. Handle only the case where err.code is 'ENOENT'.
// Read settings.json if it exists; otherwise use default values
import { readFile } from 'node:fs/promises';
const file = new URL('./settings.json', import.meta.url);
let settings = { theme: 'light' };
try {
settings = JSON.parse(await readFile(file, 'utf8'));
} catch (err) {
if (err.code !== 'ENOENT') throw err; // Rethrow any error other than ENOENT
}
console.log(settings);
When scripts/settings.json did not exist, it printed { theme: 'light' }. When I placed a file containing {"theme":"dark"}, it printed { theme: 'dark' }.
When the file content was cut off partway, as in {"theme":, the script stopped with SyntaxError: Unexpected end of JSON input. When a folder named settings.json existed, it stopped with Error: EISDIR: illegal operation on a directory, read. Because errors other than ENOENT are not hidden, you can notice when the file's content or placement is wrong.





