为了使用ES6模块,我在运行Node应用程序时使用了——experimental-modules标志。

然而,当我使用这个标志时,元变量__dirname不可用。是否有另一种方法来获得与此模式兼容的存储在__dirname中的相同字符串?


当前回答

正如Geoff指出的那样,下面的代码返回的不是模块的路径,而是工作目录。

import path from 'path';
const __dirname = path.resolve();

使用——experimental-modules

其他回答

已经有人提议通过导入公开这些变量。meta,但现在,你需要一个hack的工作,我在这里发现:

// expose.js
module.exports = {__dirname};

// use.mjs
import expose from './expose.js';
const {__dirname} = expose;
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];

Node.js 10.12有一个替代方案,不需要创建多个文件,并处理跨平台文件名中的特殊字符:

import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

在你的项目根目录下创建一个名为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的答案也是正确的。