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

Node REPL中执行console.log(__dirname)报引用错误的原因咨询

Why does __dirname work in Node.js scripts but throw a ReferenceError in the REPL?

Let me break this down for you in plain terms:

  • __dirname is a module-specific special variable that Node.js automatically injects into the execution context of every file you run as a module. Its whole purpose is to give you the absolute path of the directory containing the current script file—something that only makes sense when there's an actual physical file involved.

  • When you run a .js script (like node your-script.js), Node treats that file as a module. During the module loading process, it sets up a dedicated scope for the module and populates it with handy variables like __dirname, __filename, module, and exports to help you work with the module's specific context.

  • The REPL (Read-Eval-Print Loop) is an interactive environment where you run code line-by-line directly in Node's global context—not within the scope of a module file. Since there's no physical script file tied to the REPL session, Node has no way to determine a "module directory" to assign to __dirname. That's exactly why trying to access it throws a ReferenceError.

If you need a similar path in the REPL, you can use process.cwd() to get the current working directory (the folder you were in when you started the REPL), or load the path module and use path.resolve('.')—just keep in mind this isn't identical to __dirname (which is tied to a script's location, not your terminal's current folder).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:25:27