You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用__dirname报ReferenceError:Directory path not defined问题排查

问题原因及解决方法

原因

__dirname 是 Node.js 中 CommonJS 模块系统的内置变量,当你使用 ES 模块语法(import/export)时,这个变量并不存在,所以直接调用会抛出 ReferenceError。

解决办法

方法1:在ES模块中模拟__dirname

利用 Node.js 提供的 import.meta.url 和配套工具函数实现相同功能:

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

// 获取当前文件的完整路径
const __filename = fileURLToPath(import.meta.url);
// 从文件路径中提取目录路径
const __dirname = path.dirname(__filename);

console.log(__dirname);

方法2:切换回CommonJS模块

  • 将当前文件的后缀改为 .cjs
  • 或者在项目根目录的 package.json 中添加 "type": "commonjs"(所有 .js 文件会被当作CommonJS模块处理)
    切换后即可直接使用 __dirname。

内容的提问来源于stack exchange,提问作者Sonola Moyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:30:56