Sign Up
Go Pro Sign Up Login

How to use __dirname with ESM

Feb 12, 2021

Scott Tolinski

tldr;

import path from "path"
import { fileURLToPath } from "url"

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

The problem

With the arrival of ESM, we've gained many new abilities. With those new abilities came new syntax and new pitfalls. One-such pitfall is the lack of __filename and __dirname, two commonly used global variables available to us in common.js Node files. Read more about the differences here: https://nodejs.org/api/esm.html#esm_no_filename_or_dirname

The fix

The good news is that using path and url, two built in Node packages, we have the ability to replicate this functionality fairly easily.

Step 1. Import Node modules. These are baked in, so we don't need to install them first.

import path from "path"
import { fileURLToPath } from "url"

Step 2. Create the variables. This uses the new import.meta property, which includes meta information about your current file. Read more on that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta

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

TADA

That's it. It's a bummer that these aren't available, but it's no sweat to us to use this new technique to get them back. Just keep in mind that import.meta.url is for the current file you are in, so putting this in a utilities file or something might not yield the results you're after.

node ESM JavaScript