Last active
October 21, 2024 19:47
-
-
Save jens1101/547b90bcb5aa98b9709cdb083a5faef8 to your computer and use it in GitHub Desktop.
Common `import.meta` use cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const config = await import(new URL("config.js", import.meta.url)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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