More Node.js answers

by Danny
Published 2 min read

ES modules in Node.js do not have __dirname or __filename. Use import.meta.dirname and import.meta.filename instead, or build them from import.meta.url.

The short answer

#

__dirname and __filename only exist in CommonJS. In an ES module, use import.meta.dirname and import.meta.filename, which every supported Node.js version provides.


_10
import path from 'node:path';
_10
_10
const configPath = path.join(import.meta.dirname, 'config.json');

Why it happens

#

In CommonJS, Node.js wraps every file in a function before running it. That wrapper passes in require, module, exports, __filename and __dirname as arguments, which is why they look like globals even though they are not.

ES modules are not wrapped this way. They follow the JavaScript standard, which has no idea what a file path is, so those five variables simply do not exist. Instead, each module gets an import.meta object with information about the module itself. The main property is import.meta.url, a file: URL such as file:///home/you/app/src/index.js.

You run into the error as soon as a file is treated as an ES module. That happens when:

  • The file ends in .mjs.
  • The file ends in .js and the nearest package.json has "type": "module".
  • You copied CommonJS code, or an older tutorial, into one of those files.

How to fix it

#

Use import.meta.dirname and import.meta.filename

Node.js added these in v21.2.0 and v20.11.0. They hold the same values that __dirname and __filename would have in CommonJS:


_10
import { readFile } from 'node:fs/promises';
_10
import path from 'node:path';
_10
_10
console.log(import.meta.filename); // /home/you/app/src/index.js
_10
console.log(import.meta.dirname); // /home/you/app/src
_10
_10
const template = await readFile(
_10
path.join(import.meta.dirname, 'templates', 'email.html'),
_10
'utf8'
_10
);

Node.js 20 has reached end of life, so every supported release line has these properties. This is the recommended fix.

If a lot of old code refers to __dirname, you can define it once at the top of the file and leave the rest alone:


_10
const __dirname = import.meta.dirname;
_10
const __filename = import.meta.filename;

Build the path from import.meta.url

For code that must also run on older runtimes, convert the module URL yourself. This is the pattern you will see in a lot of existing libraries:


_10
import path from 'node:path';
_10
import { fileURLToPath } from 'node:url';
_10
_10
const __filename = fileURLToPath(import.meta.url);
_10
const __dirname = path.dirname(__filename);

Use fileURLToPath rather than reading .pathname from the URL. It decodes characters such as spaces (%20) and gives correct Windows paths like C:\app\src.

Pass a URL straight to fs

The fs functions accept URL objects as well as strings, so you can often skip path conversion entirely:


_10
import { readFile } from 'node:fs/promises';
_10
_10
const data = await readFile(new URL('./data.json', import.meta.url), 'utf8');

The second argument to new URL() makes the path relative to the current module, not the current working directory.

Switch the file back to CommonJS

If the file genuinely needs to be CommonJS, for example a config file loaded by an older tool, rename it to .cjs. Node.js treats .cjs as CommonJS regardless of the "type" field, and __dirname works again.

Common pitfalls

#
  • Using process.cwd() as a replacement. It returns the directory the process was started from, not the directory of the file, so it breaks as soon as someone runs your script from somewhere else.
  • Reading new URL(import.meta.url).pathname. It leaves %20 and other encoded characters in place and produces broken paths on Windows.
  • Expecting import.meta.dirname in a bundled browser build. It is only set for modules loaded from file: URLs, so it is undefined for modules loaded over the network or from data URLs.
  • Mixing approaches in one project. Pick import.meta.dirname for code that only targets current Node.js and stick with it.
  • Declaring const __dirname in a file that is later converted back to CommonJS. That clashes with the built-in wrapper variable and throws a SyntaxError.
#

Was this resource helpful?