Foldable.dev

Web Development

How To Use __dirname or __filename in Node.js When Using ES Modules

When using ES Modules in Node.js, __dirname & __filename aren't defined in ES module scope, so you'll have to define them yourself. Without defining them, you'll see error messages like this:

ReferenceError: __dirname is not defined in ES module scope
ReferenceError: __filename is not defined in ES module scope

Here's a short workaround:

import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);