Skip to content

Instantly share code, notes, and snippets.

@jens1101
Last active October 21, 2024 19:47
Show Gist options
  • Save jens1101/547b90bcb5aa98b9709cdb083a5faef8 to your computer and use it in GitHub Desktop.
Save jens1101/547b90bcb5aa98b9709cdb083a5faef8 to your computer and use it in GitHub Desktop.
Common `import.meta` use cases
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
// From Node >=20.11
const __filename = import.meta.filename;
const __dirname = import.meta.dirname;
// Legacy method
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const config = await import(new URL("config.js", import.meta.url));
import { readFile } from "fs/promises";
const fileUrl = new URL('./package.json', import.meta.url);
const fileContents = await readFile(fileUrl, { encoding: 'utf8' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment