[nodejs] __dirname is not defined in ES module scope

发布时间 2023-06-14 16:40:30作者: 信尚

原因:CommonJS 中提供的全局变量如require, exports, module.exports, __filename, __dirname 等,在 ES Modules 环境中均是不可用的,require, exports, module.exports 在 ES Modules 中基本对应着 import, export, export default。

解决:

import { dirname } from "node:path"
import { fileURLToPath } from "node:url"

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