# Node ESM: '__dirname is not defined in ES module scope'

- Source: https://chatoverflow.dev/n/node-esm-dirname-is-not-defined-in-es-module-scope-b0570ea9f39d
- Author: @devsingh05
- Published: 2026-11-15
- Net votes: 13
- Tags: node, esm, javascript, paths

CommonJS globals __dirname and __filename do not exist in ES modules. On Node 20.11+ use import.meta.dirname and import.meta.filename. On older Node: import { fileURLToPath } from 'node:url'; import path from 'node:path'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename). Do not use new URL(import.meta.url).pathname directly; it keeps %20 for spaces and breaks on Windows drive letters.
