为了使用ES6模块,我在运行Node应用程序时使用了——experimental-modules标志。
然而,当我使用这个标志时,元变量__dirname不可用。是否有另一种方法来获得与此模式兼容的存储在__dirname中的相同字符串?
为了使用ES6模块,我在运行Node应用程序时使用了——experimental-modules标志。
然而,当我使用这个标志时,元变量__dirname不可用。是否有另一种方法来获得与此模式兼容的存储在__dirname中的相同字符串?
当前回答
节点10.12 +…
假设你正在从一个模块中工作,这个解决方案应该可以工作,并且还提供了__filename支持
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
好的事情是,你也只需要两行代码就可以支持CommonJS模块的require()。为此,你可以补充:
import { createRequireFromPath } from 'module';
const require = createRequireFromPath(__filename);
其他回答
import path from 'path';
const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname))).replace(/^\\([A-Z]:\\)/, "$1");
这段代码也适用于Windows。(替换在其他平台上是安全的,因为路径。join只在Windows上返回反斜杠分隔符)
另一个选择
import {createRequire} from 'module'; // need node v12.2.0
const require = createRequire(import.meta.url);
const __dirname = require.resolve.paths('.')[0];
在你的项目根目录下创建一个名为root-dirname.js的文件:
import { dirname } from 'path'
const dn = dirname(new URL(import.meta.url).hostname)
const __dirname = process.platform === 'win32' ? dn.substr(1) : dn // remove the leading slash on Windows
export const rootDirname = __dirname
然后在需要项目根文件夹的路径时导入rootDirname。
除此之外,Rudolf Gröhling的答案也是正确的。
我使用:
import path from 'path';
const __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
decodeURI很重要:在我的测试系统的路径中使用空格和其他东西。
Path.resolve()处理相对url。
编辑:
修复支持windows (/C:/…= > C: /…):
import path from 'path';
const __dirname = (() => {let x = path.dirname(decodeURI(new URL(import.meta.url).pathname)); return path.resolve( (process.platform == "win32") ? x.substr(1) : x ); })();
process.cwd()
从文档:
process.cwd()方法返回 node . js的过程。