__dirname in ES modules

It's gone in ESM. Here is the replacement, and the newer, nicer one.

SNP 084 #45A Filed js node

In Node 20.11 and newer, it's built in:

javascript
const dir = import.meta.dirname
const file = import.meta.filename

Before that, you build it from import.meta.url:

javascript
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'

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

For reading a file next to the module, you can skip paths entirely and pass a URL:

javascript
import { readFile } from 'node:fs/promises'

const text = await readFile(new URL('./data.txt', import.meta.url), 'utf8')