javascript / intermediate
Snippet
Cross-platform Paths in ESM
In ES modules (ESM), common variables like __dirname are not available. Using the URL constructor with import.meta.url is the standard, cross-platform way to resolve paths relative to the current file in Node.js.
snippet.js
1
2
3
4
5
6
import { readFile } from 'node:fs/promises';const configUrl = new URL('./config.json', import.meta.url);const data = await readFile(configUrl, 'utf-8');console.log(JSON.parse(data));
nodejs
Breakdown
1
new URL('./config.json', import.meta.url);
Creates a URL object pointing to a file relative to the current module's location.
2
await readFile(configUrl, 'utf-8');
The fs/promises methods can accept URL objects directly, making path handling cleaner.