Mimicking __dirname and __filename in ESM modules in Node.js

CommonJS files running in Node.js have access to two very helpful variables:

  1. __dirname - the directory in which the current file lives.
  2. __filename - the full path to the current file.

In ECMAScript modules, however, these are no longer available by default. Fortunately, you can recreate them yourself to get the same information that to the import.meta.url property:

import { fileURLToPath } from "node:url";
import path from "node:path";

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

The import.meta.url property is a file URL, not a file path, so you first have to convert it into a file path. After that, you just need to use path.dirname() to pull off the directory.

Master Your Time as a Tech Lead

Free E-book - Managing Your Interrupt Rate

Take Control of Your Calendar

  • Understanding interrupt patterns
  • Strategies for time management
  • Communication techniques
  • Productivity optimization

The popular blog post series plus frequently asked questions, all in one convenient PDF.

Download Your Free Copy

Get immediate access to proven strategies for managing interruptions.