Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
ReferenceError: __dirname is not defined after switching to ES Modules
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);The Solution //
Setting "type": "module" in package.json (or using .mjs files) disables CommonJS's auto-injected __dirname and __filename entirely ā ESM is a strict spec and doesn't provide them. Reconstruct them manually from import.meta.url using the node:url and node:path core modules.
The Error //
Using process.argv indices without accounting for the first two fixed entries
// node script.js --env=prod
// process.argv = ['/usr/bin/node', '/app/script.js', '--env=prod']
const userArgs = process.argv.slice(2); // ['--env=prod']The Solution //
process.argv[0] is always the path to the node executable and process.argv[1] is always the path to the script being run ā the actual user-supplied arguments start at index 2. Beginners frequently read process.argv[0] expecting their first CLI flag and get the node binary path instead.