ZL
About Articles Contact
Published on Nov 28, 2023
Filed under:
#node,
#splendidlabz

The easiest way to get __dirname in Node with ES Modules

Getting the directory name (or short for dirname) is extremely simple in Node prior to ES Modules (ESM).

All we had to do was use the __dirname global variable.

console.log(__dirname) // This will show the directory

Unfortunately, __dirname is not supported in ES Modules. So if we want __dirname, we need to use a rather round-about way to retrieve it.

How to get dirname in ESM

The easiest way to get dirname in ESM is to use three utilities that Node provides us with

  • import.meta.url — This gives you the file path to the current file
  • fileUrlToPath — This strips away the file:// protocol so the URL can be used in path.
  • path — This is a utility you can use to specify paths in Node

The complete code looks like this:

import { fileURLToPath } from 'url'
import path from 'path'
const __dirname = path.dirname(fileURLToPath(import.meta.url))

This code can be really complicated to remember. So I abstracted it into a dirname function in Splendid UI.

The easier way to get dirname

First, install Splendid UI.

Terminal window
npm install splendidlabz

Then import dirname from the node subpath.

import { dirname } from 'splendidlabz/node'

Then you just have to pass the import.meta.url into dirname and you’ll get the __dirname value.

const __dirname = dirname(import.meta.url)

That’s it!

I hope this makes things easier for you when using Node :)

Further reading

  • Splendid UI
  • dirname utility documentation
Previous Analytics and Ads Next JavaScript Mental Models

Join My Newsletter

I share what I’m learning on this newsletter: code, building businesses, and living well.

Sometimes I write about technical deep-dives, product updates, musings on how to live, and sometimes my struggles and how I’m breaking through.

Regardless of the type of content, I do my best to send you an update every week.

If you’re into making things and growing as a person, you’ll probably feel at home here.

“

Zell’s writing is very accessible to newcomers because he shares his learning experience. He covers current topics and helps all readers level up their web development skills. Must subscribe.

Chen Hui Jing
Chen Hui Jing — Web Developer
The Footer

General

Home About Contact Testimonials Tools I Use

Projects

Magical Dev School Splendid Labz

Socials

Youtube Instagram Tiktok Github Bluesky X

Follow Along

Email RSS
© 2013 - 2025 Zell Liew / All rights reserved / Terms