[英]path.resolve vs. relative path in Node.js?
I often see examples in node like:我经常在节点中看到这样的例子:
process.env.GOOGLE_APPLICATION_CREDENTIALS = path.resolve(__dirname, 'credentials.json')
I understand that path
is a useful module when dealing with more complex situations, but in this case, why not just use我知道
path
在处理更复杂的情况时是一个有用的模块,但在这种情况下,为什么不直接使用
process.env.GOOGLE_APPLICATION_CREDENTIALS = './credentials.json'
? ?
From the Documentation :从文档中:
The directory name of the current module.
当前模块的目录名。 This is the same as the path.dirname() of the __filename.
这与 __filename 的 path.dirname() 相同。
This means when using this:这意味着使用它时:
process.env.GOOGLE_APPLICATION_CREDENTIALS = './credentials.json'
NodeJS will look for credentials.json
in the current working directory NodeJS 将在当前工作目录中查找
credentials.json
While when using this:使用时:
process.env.GOOGLE_APPLICATION_CREDENTIALS = path.resolve(__dirname, 'credentials.json')
NodeJS will look for credentials.json
in the same directory where this module is NodeJS 将在该模块所在的同一目录中查找
credentials.json
Lets say you have a directory structure like this:假设您有这样的目录结构:
/
+-- home
| +-- USERNAME
| +-- project
| +-- index.js
| +-- credentials.json
if you run the following commands (from the root directory /
):如果您运行以下命令(从根目录
/
):
cd home/USERNAME/project
node index.js
The code will work just fine in both cases.在这两种情况下,代码都可以正常工作。
But if you run it like this但是如果你这样运行它
node home/USERNAME/project/index.js
With path.resolve
you'll get: home/USERNAME/project/credentials.json
which is correct使用
path.resolve
你会得到: home/USERNAME/project/credentials.json
这是正确的
and without it you'll get: ./credentials.json
, which is wrong as your current directory is /
.如果没有它,您将得到:
./credentials.json
,这是错误的,因为您当前的目录是/
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.