Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

ReferenceError: __dirname is not defined in ES module scope: how to fix it

Node.js runs the file as an ES module, because package.json says "type": "module", the file ends in .mjs, or it uses import syntax, and ES modules have no __dirname, __filename or require. Use import.meta.dirname and import.meta.filename (Node.js 20.11 and 21.2 and later), path.dirname(fileURLToPath(import.meta.url)) on older versions, createRequire for require, or rename the file to .cjs to keep it CommonJS.

By Livops team, the people who build and run LivopsUpdated

As Node.js 24 prints it, when a .js file uses __dirname in a package whose package.json has "type": "module" (stack trimmed, paths shortened):

file:///app/index.js:1
console.log(__dirname)
            ^

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 '/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///app/index.js:1:13

__filename gives the same message with its own name. The sibling for require adds a hint[6]:

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

The second line, about "type": "module", appears only for a .js file under such a package.json[6]; a .mjs file gets the first line alone. This page explains why the names are missing, gives the four fixes, and covers why the error often shows up only after a deploy. It is a Node.js error, not one specific to any host.

What does the error mean?

In CommonJS, Node.js wraps each file in a function before running it, (function(exports, require, module, __filename, __dirname) { … }), and that is where __dirname, __filename and require come from[3]. ES modules are not wrapped. Node’s docs list it among the differences: no require, exports or module.exports, and no __filename or __dirname[1]. So in an ES module these are plain undefined names, and the first line that uses one throws.

Node.js runs a file as an ES module when[2]:

  • it ends in .mjs;
  • it ends in .js and the nearest parent package.json has "type": "module";
  • it ends in .js with no type field to say otherwise, and contains ES module syntax — import or export statements, import.meta, or top-level await. This syntax detection is on by default since Node.js 22.7.0 and 20.19.0[2].

A .cjs file is always CommonJS, whatever package.json says[2].

Fix 1: import.meta.dirname and import.meta.filename

The direct replacements[1]:

import path from 'node:path'

const configPath = path.join(import.meta.dirname, 'config.json')
console.log(import.meta.filename)   // was __filename

import.meta.dirname is the directory of the current module and import.meta.filename its full path, with symlinks resolved[1]. Both were added in Node.js 21.2.0 and 20.11.0, and are no longer experimental since 24.0.0 and 22.16.0[1]. They exist only for modules loaded from file: URLs[1], which is every file on disk.

On an older Node.js they are undefined, and the error moves: path.join(undefined, …) throws a TypeError about the "path" argument instead. If you must support those versions, use fix 2.

Fix 2: fileURLToPath(import.meta.url), for older Node.js

Works on every Node.js that runs ES modules. import.meta.filename is the same as url.fileURLToPath() of import.meta.url[1], and import.meta.dirname is its path.dirname()[1]:

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

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

fileURLToPath decodes percent-encoded characters and returns a valid absolute path for the platform[5], so do not slice the URL string by hand: a path with spaces breaks that way.

Fix 3: createRequire, when you need require

import covers most uses: it can load CommonJS packages too[1]. Where you really need require, build one for the current file with module.createRequire()[1][4]:

import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)
const legacy = require('./legacy-config.cjs')

For a JSON file you do not need it: import attributes load JSON in an ES module, and the JSON comes back as the default export[1]:

import packageConfig from './package.json' with { type: 'json' }

JSON modules stopped being experimental in Node.js 23.1.0, 22.12.0, 20.18.3 and 18.20.5[1].

Fix 4: keep the file CommonJS

If the code is CommonJS, and only one file or the package’s setting makes it an ES module, change that instead:

  • One file: rename it to .cjs, as the error message itself suggests[6]. A .cjs file is CommonJS even in a "type": "module" package[2].
  • The whole package: set "type": "commonjs", or remove the field. Then .js files run as CommonJS[2]. Rename the files that use import to .mjs: without a type field Node.js would detect them, but its docs say that costs performance and ask packages to be explicit[2].

Mixing the two in one file does not work. A file with no type that uses both __dirname and top-level await stops with a different message, because Node.js cannot tell which format was meant[6]:

ReferenceError: Cannot determine intended module format because both '__dirname' and top-level await are present. If the code is intended to be CommonJS, wrap await in an async function. If the code is intended to be an ES module, use import.meta.dirname instead.
  code: 'ERR_AMBIGUOUS_MODULE_SYNTAX'

Why it appears only after a deploy

The code that runs on the server is often not the code you run locally. The usual reasons:

  • The build output changed format. With --module nodenext, TypeScript emits each .ts file as an ES module if the nearest package.json has "type": "module", and as CommonJS otherwise; .mts always becomes ESM and .cts CommonJS[7]. Adding "type": "module" turns the same source into ES module output, and a __dirname in it now throws.
  • A bundler emits ESM. __dirname exists only in CommonJS; tsup, for example, fills it in for its ESM output only when its shims option is on, as path.dirname(fileURLToPath(import.meta.url))[8].
  • "type": "module" was added to package.json, often to use a package that ships only as an ES module (see ERR_REQUIRE_ESM). Every .js file in the package becomes an ES module at once[2], including scripts nobody touched.
  • A newer Node.js on the server. A .js file with no type field that uses import runs as an ES module on Node.js 22.7.0 and 20.19.0 or later[2]; an older Node.js stopped at the import with Cannot use import statement outside a module. The new Node.js gets further, to the first __dirname.
  • An older Node.js on the server, the reverse case: code that uses import.meta.dirname runs on your Node.js 22 and gets undefined on a server older than 20.11.0[1].

How to confirm the fix

Run the file the way the server runs it — the built output, with the server’s Node.js version:

node --version
node dist/index.js

To see which format Node.js uses for a file, check its extension and the type field of the nearest package.json above it[2]. In that package.json’s folder:

node -p "require('./package.json').type"

module means .js files there are ES modules; undefined means CommonJS unless the file contains ES module syntax[2].

On Livops

  • Where it shows. The build passes, the app stops right after it starts, and the deploy fails as start_failed. The Logs page shows the app’s last words, the ReferenceError among them, often with a Tip: line under it. A web app’s previous version keeps running; a bot’s previous version is stopped first, so the bot is down until a deploy succeeds. See The app did not start.
  • Node.js versions. Livops has Node.js 22 and 24. It reads .nvmrc and .node-version, and devEngines.runtime.version in package.json can ask for 22 or 24. Both versions have import.meta.dirname and import.meta.filename, so fix 1 works without a fallback.
  • The start command decides which file runs. Set it in Settings → Start. Without one, Livops looks for the start script in package.json, then the main field, then index.js, server.js, app.js, main.js. In a TypeScript project, build first and start the built file, for example node dist/main.js — that built file is the one to test locally. See No start command.

A Node.js web app costs 39 credits a month; a bot or worker 19. Running a Node.js server in production is covered in Node.js hosting.

Questions

Why is __dirname not defined in ES module scope?

In CommonJS, Node.js wraps every file in a function that passes in __dirname, __filename, require, module and exports. ES modules are not wrapped that way, so those names do not exist there. Node's docs list them under the differences between ES modules and CommonJS.

What replaces __dirname in an ES module?

import.meta.dirname, and import.meta.filename for __filename. They were added in Node.js 21.2.0 and 20.11.0 and are no longer experimental since 24.0.0 and 22.16.0. On older versions use path.dirname(fileURLToPath(import.meta.url)).

Why does my file count as an ES module?

Node.js treats a file as an ES module if it ends in .mjs, if it ends in .js and the nearest package.json has "type": "module", or, with no type field at all, if it contains import, export, import.meta or top-level await. The error message says which one when it is the type field.

How do I use require in an ES module?

Prefer import. Where you need require, for example for a JSON file or a package that only works with require, build one: import { createRequire } from 'node:module' and const require = createRequire(import.meta.url).

Why does it work on my machine but fail after deploy?

The server runs different code or a different Node.js. Usually the build output changed format: TypeScript emits ES modules once package.json has "type": "module", and a bundler can emit ESM. A newer Node.js also detects ES module syntax by default, from 22.7.0 and 20.19.0.

Can I just remove "type": "module" from package.json?

Only if your code is CommonJS. Without it, .js files run as CommonJS, and files that use import should be renamed to .mjs; Node.js can detect them, but at a performance cost. To keep one file CommonJS inside a type module package, rename it to .cjs instead.

Which Node.js version does Livops run?

Node.js 22 or 24, chosen with .nvmrc, .node-version or devEngines.runtime.version in package.json. Both have import.meta.dirname and import.meta.filename.

Sources

  1. Node.js Docs — Modules: ECMAScript modules (nodejs.org). Checked .
  2. Node.js Docs — Modules: Packages (nodejs.org). Checked .
  3. Node.js Docs — Modules: CommonJS modules (nodejs.org). Checked .
  4. Node.js Docs — Modules: node:module API (nodejs.org). Checked .
  5. Node.js Docs — URL (nodejs.org). Checked .
  6. Node.js v24.16.0 source — lib/internal/modules/esm/module_job.js (raw.githubusercontent.com). Checked .
  7. TypeScript Handbook — Modules: Reference (typescriptlang.org). Checked .
  8. tsup — documentation (raw.githubusercontent.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Node app

Got a question? — @livops_uz