日本語

Fixing “__dirname is not defined” in Node.js

​​Node.js​ES Modules,JavaScript,Troubleshooting

You see ReferenceError: __dirname is not defined in ES module scope in your terminal when a file that Node.js loads as an ES module uses __dirname. __dirname only works in CommonJS files (the module format that uses require and has been in Node.js from the start). In an ES module, replace it with import.meta.dirname and the error goes away.

This happens after you add "type": "module" to package.json so you can use import, and then try to read a config file or template in the same folder as the script with path.join(__dirname, ...). I reproduced the error in my test environment, checked the full message, and confirmed that the fix removes it.

Note

My test environment was Ubuntu 24.04. I mainly tested with Node.js 24.22.1 (npm 11.19.1), and for comparison I also ran the same files with Node.js 22.23.4 and 20.10.0. For Node.js 20.10.0, I used the Linux binary distributed on nodejs.org. I did not test Windows or macOS, running .ts files directly, or the same-named errors that appear inside tools such as webpack or Jest.

The full error message

In the test environment (Ubuntu 24.04, Node.js 24.22.1), I ran npm init -y, then set "type" to "module" in package.json with npm pkg set type=module. In the same folder, I put a message.txt containing only "hello" and this index.js. The script reads message.txt relative to the script's location and prints its contents.

js
import { readFileSync } from 'node:fs';
import path from 'node:path';

const file = path.join(__dirname, 'message.txt');
console.log(readFileSync(file, 'utf8').trim());

Running node index.js stopped with the output below (exit code 1). I replaced the paths with example values.

text
$ node index.js
file:///path/to/app/index.js:4
const file = path.join(__dirname, 'message.txt');
                       ^

ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/path/to/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///path/to/app/index.js:4:24
    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)

Node.js v24.22.1

The main error is the ReferenceError: __dirname is not defined in ES module scope line, which means __dirname is not defined in an ES module. The file:///path/to/app/index.js:4 line at the top and the ^ mark show the line and column where execution stopped.

The English sentence below it explains why Node.js treated this file as an ES module: the file has a .js extension and package.json contains "type": "module". To use CommonJS instead, rename the file to .cjs.

A file with the .mjs extension is always read as an ES module, regardless of the type field in package.json. I set package.json to "type": "commonjs" and ran index.mjs with the same contents. It produced the same ReferenceError. In this case there is no explanatory sentence, and the stack trace follows directly below the ReferenceError line.

Using __filename gives the same result: ReferenceError: __filename is not defined in ES module scope. The official documentation on the differences between ES modules and CommonJS says that __filename and __dirname are not available in ES modules and that you should use import.meta.filename and import.meta.dirname instead.

Replacing it with import.meta.dirname

In Node.js 20.11.0 or later (or 21.2.0 or later in the 21.x line), you only need to replace __dirname with import.meta.dirname and __filename with import.meta.filename. I also added lines that print both values so I could check them.

js
import { readFileSync } from 'node:fs';
import path from 'node:path';

console.log(import.meta.dirname);
console.log(import.meta.filename);

const file = path.join(import.meta.dirname, 'message.txt');
console.log(readFileSync(file, 'utf8').trim());
text
$ node fixed-meta.js
/path/to/app
/path/to/app/fixed-meta.js
hello

No error occurred. import.meta.dirname contained the folder that holds the file, and import.meta.filename contained the file's absolute path. I also changed to the root directory (/) and ran node /path/to/app/fixed-meta.js, and the output was the same. As with __dirname, the values come from the script's location, not from the folder where you run the command. Node.js 22.23.4 gave the same result.

According to the official documentation for import.meta.dirname, these two properties were added in Node.js 21.2.0 and 20.11.0, and they were no longer experimental in Node.js 24.0.0. They also only work in modules loaded from local files via file:.

Warning

In Node.js versions before these properties were added (I tested 20.10.0), writing import.meta.dirname or import.meta.filename does not raise an error. Their values are undefined. When I ran fixed-meta.js above with Node.js 20.10.0, it printed undefined on two lines, and then path.join stopped with TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined. If you need to support older Node.js versions, use the approach in the next section.

Using import.meta.url for older Node.js versions

Even in Node.js versions that do not have import.meta.dirname, you can use import.meta.url, which is the file:///... URL of the module. Convert this URL to a path with fileURLToPath, then get the folder with path.dirname. The result is the same value as __dirname. If you declare variables with these names at the top of the file, the rest of the code can stay unchanged.

js
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

console.log(import.meta.url);
const file = path.join(__dirname, 'message.txt');
console.log(readFileSync(file, 'utf8').trim());
text
$ node fixed-url.js
file:///path/to/app/fixed-url.js
hello

Node.js 24.22.1 and 20.10.0 both produced the same output.

Using new URL if you only need to read a file

If you use __dirname only to read a file next to the script, you don't need to build a folder path at all. new URL('./message.txt', import.meta.url) creates a URL for message.txt relative to the script. Most functions in node:fs accept a file: URL object in place of a path string (official documentation on passing file URLs as paths).

js
import { readFileSync } from 'node:fs';

const file = new URL('./message.txt', import.meta.url);
console.log(readFileSync(file, 'utf8').trim());

Running this file printed hello without an error.

Keeping CommonJS by renaming the file to .cjs

If the file doesn't need import, you can follow the error message's suggestion: rename it to .cjs and write it with require. A .cjs file is read as CommonJS even when package.json has "type": "module", so __dirname works as is.

js
const { readFileSync } = require('node:fs');
const path = require('node:path');

const file = path.join(__dirname, 'message.txt');
console.log(readFileSync(file, 'utf8').trim());

With "type": "module" still set, I ran this index.cjs and it printed hello without an error. In the other direction, adding an import statement to a .cjs file and running it stopped with SyntaxError: Cannot use import statement outside a module. If you rename the file, convert the whole file to require syntax. The official documentation on how Node.js determines the module system explains how the file extension and the type field in package.json decide the format.

​Posted by 86