node.js 中的 __dirname 和 ./ 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8131344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:46:45  来源:igfitidea点击:

What is the difference between __dirname and ./ in node.js?

node.js

提问by thisissami

When programming in Node.js and referencing files that are located somewhere in relation to your current directory, is there any reason to use the __dirnamevariable instead of just a regular ./? I've been using ./ thus far in my code and just discovered the existence of __dirname, and essentially want to know whether it would be smart to convert my ./'s to that, and if so, why that would be a smart idea.

在 Node.js 中编程并引用与当前目录相关的某个位置的文件时,是否有任何理由使用__dirname变量而不是常规的./?到目前为止,我一直在我的代码中使用 ./ 并且刚刚发现 的存在__dirname,并且基本上想知道将我的 ./ 转换为它是否明智,如果是这样,为什么这会是一个聪明的主意.

回答by d512

The gist

要点

In Node.js, __dirnameis always the directory in which the currently executing script resides (see this). So if you typed __dirnameinto /d1/d2/myscript.js, the value would be /d1/d2.

在 Node.js 中,__dirname始终是当前正在执行的脚本所在的目录(请参阅此)。所以,如果你键入__dirname/d1/d2/myscript.js,该值会/d1/d2

By contrast, .gives you the directory from which you ran the nodecommand in your terminal window (i.e. your working directory) when you use libraries like pathand fs. Technically, it starts out as your working directory but can be changed using process.chdir().

相比之下,.让你从中运行的目录node在终端窗口的命令,当您使用库,例如(即你的工作目录)pathfs。从技术上讲,它最初是您的工作目录,但可以使用process.chdir().

The exception is when you use .with require(). The path inside requireis always relative to the file containing the call to require.

例外是当您使用.with 时require()。里面的路径require总是相对于包含调用的文件require

For example...

例如...

Let's say your directory structure is

假设您的目录结构是

/dir1
  /dir2
    pathtest.js

and pathtest.jscontains

pathtest.js包含

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

你也是

cd /dir1/dir2
node pathtest.js

you get

你得到

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2so that's what .resolves to. Since pathtest.jsis located in /dir1/dir2that's what __dirnameresolves to as well.

您的工作目录就是/dir1/dir2这样.解决的。由于pathtest.js位于,/dir1/dir2这也是__dirname解决的问题。

However, if you run the script from /dir1

但是,如果您从 /dir1

cd /dir1
node dir2/pathtest.js

you get

你得到

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1so that's what .resolved to, but __dirnamestill resolves to /dir1/dir2.

在这种情况下,您的工作目录就是/dir1这样.解析的,但__dirname仍然解析为/dir1/dir2.

Using .inside require...

使用.require...

If inside dir2/pathtest.jsyou have a requirecall into include a file inside dir1you would alwaysdo

如果在里面dir2/pathtest.js你有一个require电话在里面包含一个文件,dir1总是会这样做

require('../thefile')

because the path inside requireis always relative to the file in which you are calling it. It has nothing to do with your working directory.

因为里面的路径require总是相对于你调用它的文件。它与您的工作目录无关。

回答by fent

./refers to the current working directory, except in the require()function. When using require(), it translates ./to the directory of the current file called. __dirnameis always the directory of the current file.

./指的是当前工作目录,require()函数中除外。使用时require(),它会转换./为当前调用文件的目录。__dirname始终是当前文件的目录。

For example, with the following file structure

例如,具有以下文件结构

/home/user/dir/files/config.json

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cdinto /home/user/dirand run node dir.jsI will get

如果我cd进入/home/user/dir并运行,node dir.js我会得到

{ hello: 'world' }
text file

But when I run the same script from /home/user/I get

但是当我运行相同的脚本时,/home/user/我得到

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./worked with requirebut not for fs.readFileSync. That's because for fs.readFileSync, ./translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txtdoes not exist.

使用./require但不用于fs.readFileSync. 那是因为 for fs.readFileSync,./转换为 cwd (在本例中为/home/user/)。并且/home/user/files/somefile.txt不存在。