Unable to use __dirname
__dirname
yescommonjs
Built-in variables for specification.
If usedesm
This variable will not be automatically injected.
existcommonjs
Injected__dirname
, __filename
, module
, exports
, require
Five built-in variables are used to implement the ability to import and export. And inesm
The implementation method is different.
existesm
In the import and export of modules, it is obvious thatexport/import
, naturally won't use it againexports/require
, same__dirname
, __filename
There are also corresponding writing methods.
Method 1
First, usenode:url
URLs in modules andfileURLToPath
Functions parse and convert URLs.
Then, use the first parameter of the URL constructor to pass in ".", that is, the relative path of the current directory, and then combine it with
to get the URL of the current directory.
Finally, usefileURLToPath
The function converts the URL to a file path to get the required__dirname
// Method 1import { URL, fileURLToPath } from "node:url"; // Get __filenamefunction getCurrnetFile () { return fileURLToPath(); } // Get __dirnamefunction getCurrnetDir () { const url = new URL(".", ); return fileURLToPath(url); }
Method 2
This method is usednode:path
In the moduledirname
Functions andnode:url
In the modulefileURLToPath
function.
First, usefileURLToPath
The function will
Convert to file path and get the path of the current file__filename
。
Then, usedirname
Function converts file path to path to directory where__dirname
, thus obtaining__dirname
。
// Method 2import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; // Get __filenamefunction getCurrnetFile () { return fileURLToPath(); } // Get __dirnamefunction getCurrnetDir () { const __filename = fileURLToPath(); const __dirname = dirname(__filename); return __dirname; }
You can see that a key API is used
,actually
yesECMA
Part of the specification:
The object exposes context-specific metadata to a JavaScript module.
It contains information about the module, like the module’s URL.
What it means,
Provides context information for a module.
In short, both of the above methods are simulated and obtained in ESM__dirname
function.
They use
Get the URL of the module, and then use the relevant built-in module to parse the URL or file path, thereby obtaining the directory path where the current module is located
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.