node __dirname not defined
从节点手册中,我可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ node > console.log(__dirname) ReferenceError: __dirname is not defined at repl:1:14 at REPLServer.eval (repl.js:80:21) at Interface. (repl.js:182:12) at Interface.emit (events.js:67:17) at Interface._onLine (readline.js:162:10) at Interface._line (readline.js:426:8) at Interface._ttyWrite (readline.js:603:14) at ReadStream. (readline.js:82:12) at ReadStream.emit (events.js:88:20) at ReadStream._emitKey (tty.js:320:10) |
尝试制作脚本
1 | console.log(__dirname); |
并运行它:
1 | node a.js |
您将看到
添加了背景说明:
在这里已有的答案的基础上,您可以在REPL中定义它:
1 | __dirname = path.resolve(path.dirname('')); |
要么:
1 | __dirname = path.resolve(); |
If no
path segments are passed,path.resolve() will return the absolute path of the current working directory.
或@Jthorpe的替代品:
1 2 3 | __dirname = process.cwd(); __dirname = fs.realpathSync('.'); __dirname = process.env.PWD |
正如@qiao所说,您不能在节点repl中使用
尽管它不能解决此问题,但我想添加它,因为它可能会对其他人有所帮助。
dirname前应该有两个下划线,而不是下划线(
http://nodejs.org/docs/latest/api/globals.html#globals_dirname
似乎您也可以这样做:
1 | __dirname=fs.realpathSync('.'); |
当然,不要忘记
(它在节点脚本中并不是真正的全局变量,只是在模块级别定义的)
在ES6中使用:
1 2 | import path from 'path'; const __dirname = path.resolve(); |
当使用
我以SYSTEM用户身份从批处理文件运行脚本,并且所有
这是通过触发错误并从e.stack提取路径来获取真实路径的一种非常骇人的方法。不使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // this should be the name of currently executed file const currentFilename = 'index.js'; function veryHackyGetFolder() { try { throw new Error(); } catch(e) { const fullMsg = e.stack.toString(); const beginning = fullMsg.indexOf('file:///') + 8; const end = fullMsg.indexOf('\/' + currentFilename); const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\'); return dir; } } |
用法
1 | const dir = veryHackyGetFolder(); |