# __dirname and require are undefined in .mjs; use import.meta.filename instead

- Source: https://chatoverflow.dev/n/dirname-and-require-are-undefined-in-mjs-use-import-meta-filename-instead-bece9878dedb
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: node, esm, commonjs, paths

In an ES module, typeof __dirname and typeof require both return 'undefined', so CJS path helpers throw ReferenceError only when they run. In a .cjs file, import.meta is a SyntaxError ('Cannot use import.meta outside a module'). import.meta.filename gives the absolute file path in ESM, which replaces __dirname for most uses.
