从节点手册中我看到我可以获取文件的目录__dirname
,但是从REPL看来这似乎是未定义的.这是我的误解还是错误在哪里?
$ node
> console.log(__dirname)
ReferenceError: __dirname is not defined
at repl:1:14
at REPLServer.eval (repl.js:80:21)
at Interface.<anonymous> (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.<anonymous> (readline.js:82:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty.js:320:10)
Run Code Online (Sandbox Code Playgroud)
qia*_*iao 164
__dirname
仅在脚本中定义.它在REPL中不可用.
尝试制作一个剧本 a.js
console.log(__dirname);
Run Code Online (Sandbox Code Playgroud)
并运行它:
node a.js
Run Code Online (Sandbox Code Playgroud)
你会看到__dirname
印刷的.
添加了背景说明:__dirname
表示"此脚本的目录".在REPL中,您没有脚本.因此,__dirname
没有任何实际意义.
AMS*_*777 89
如果您正在使用Node.js modules,__dirname
并且__filename
不存在。
不需要,exports,module.exports,__filename,__dirname
这些 CommonJS 变量在 ES 模块中不可用。
require
可以使用module.createRequire()
.可以通过以下方式在每个文件中创建
__filename
和 的等效项:__dirname
import.meta.url
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
Run Code Online (Sandbox Code Playgroud)
https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname
c24*_*24w 74
基于现有答案,您可以在REPL中定义:
__dirname = path.resolve(path.dirname(''));
Run Code Online (Sandbox Code Playgroud)
要么:
__dirname = path.resolve();
Run Code Online (Sandbox Code Playgroud)
或@ Jthorpe的替代品:
__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD
Run Code Online (Sandbox Code Playgroud)
正如@qiao所说,你不能__dirname
在节点repl中使用.但是,如果您需要在控制台中使用此值,则可以使用path.resolve()
或path.dirname()
.虽然,path.dirname()
只会给你一个"." 所以,可能没那么有用.一定要require('path')
.
我也试图加入我的路径,path.join(__dirname, 'access.log')
但它抛出了同样的错误。
这是我修复它的方法:
我首先导入了路径包并声明了一个名为 的变量__dirname
,然后调用了resolve
路径方法。
在 CommonJS 中
var path = require("path");
var __dirname = path.resolve();
Run Code Online (Sandbox Code Playgroud)
在 ES6+ 中
import path from 'path';
const __dirname = path.resolve();
Run Code Online (Sandbox Code Playgroud)
快乐编码......
小智 6
在ES6中使用:
import path from 'path';
const __dirname = path.resolve();
Run Code Online (Sandbox Code Playgroud)
当使用调用节点时也可用 --experimental-modules
小智 5
-> 在 ES6 版本使用:
import path from "path"
const __dirname = path.resolve();
Run Code Online (Sandbox Code Playgroud)
-> 像这样使用它,例如:
res.sendFile(path.join(__dirname ,'views','shop.html'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
66233 次 |
最近记录: |