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

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


当前回答

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

其他回答

我使用这个选项,因为路径以file://开始,只需删除该部分。

const __filename = import.meta.url.slice(7);
const __dirname = import.meta.url.slice(7, import.meta.url.lastIndexOf("/"));

因为其他答案虽然有用,但没有涵盖跨平台情况(Windows POSIX)和/或路径解析,而不是__dirname或__filename,在所有地方重复这种代码有点冗长:

import { dirname, join } from 'path'
import { fileURLToPath } from 'url'

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

const somePath = join(__dirname, '../some-dir-or-some-file')

我刚刚发布了一个名为esm-path的NPM包来帮助完成这种循环任务,希望它也能对其他人有用。

它有文档记载,但在这里如何使用它:

import { getAbsolutePath } from 'esm-path'

const currentDirectoryPath = getAbsolutePath(import.meta.url)
console.log(currentDirectoryPath)

const parentDirectoryPath = getAbsolutePath(import.meta.url, '..')
console.log(parentDirectoryPath)

// Adapt the relative path to your case
const packageJsonFilePath = getAbsolutePath(import.meta.url, '../package.json')
console.log(packageJsonFilePath)

// Adapt the relative path to your case
const packageJsonFilePath = getAbsolutePath(import.meta.url, '..' , 'package.json')
console.log(packageJsonFilePath)

只需使用path.resolve()方法即可。

import { resolve } from 'path';

app.use('/public/uploads', express.static(resolve('public', 'uploads')))
import path from 'path';
import { fileURLToPath } from 'url';

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


// do not use the following code which is bad for CJK characters
const __filename = new URL('', import.meta.url).pathname;

我创建了这个模块es-dirname,它将返回当前脚本dirname。

import dirname from 'es-dirname'

console.log(dirname())

它既适用于CommonJs脚本,也适用于Windows和Linux上的ES模块。

打开一个问题,如果有一个错误,因为脚本一直在我的项目中工作,但在其他一些情况下可能会失败。因此,不要在生产环境中使用它。这是一个临时的解决方案,我相信Node.js团队在不久的将来会发布一个健壮的方法来实现它。