Course contentsShow
← JavaScript
Lesson 1546 of 2,72333. JavaScript in Node.jsFree lesson

__dirname and __filename in ESM

Replace __dirname and __filename in ES modules using import.meta.url and fileURLToPath.

__dirname and __filename in ESM

You'll learn how to recreate __dirname and __filename in ES modules using import.meta.url and fileURLToPath.

The Problem

In CommonJS modules, Node.js automatically provides __dirname (the directory of the current file) and __filename (the full path to the current file). These are incredibly useful for constructing file paths relative to your module's location.

But in ES modules, __dirname and __filename don't exist. If you try to use them, you'll get a ReferenceError.

The ESM Solution

ES modules give you import.meta.url instead—a special URL string representing the current module's location. It looks like "file:///path/to/your/file.js".

To convert this URL into usable file paths, you need Node.js's url module:

import { fileURLToPath } from 'url';
import path from 'path';

// Recreate __filename
const __filename = fileURLToPath(import.meta.url);

// Recreate __dirname
const __dirname = path.dirname(__filename);

console.log(__filename); // /Users/you/project/app.js
console.log(__dirname);  // /Users/you/project

How It Works

Think of import.meta.url as a raw address label written in URL format. fileURLToPath() translates that URL into a normal file system path your operating system understands. Then path.dirname() strips off the filename to give you just the directory.

When You Need This

Anytime you're building paths relative to your module's location—loading config files, requiring assets, or creating output directories—you'll use this pattern.

Key Takeaway: In ESM, replace __dirname and __filename by converting import.meta.url with fileURLToPath() and path.dirname().