node.js中的__dirname和./有什么区别? [英] What is the difference between __dirname and ./ in node.js?

查看:117
本文介绍了node.js中的__dirname和./有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 __dirname variable 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始终是当前正在执行的脚本所在的目录(看到这个).因此,如果在/d1/d2/myscript.js中键入__dirname,则值为/d1/d2.

The gist

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

相反,当使用诸如pathfs之类的库时,.为您提供在终端窗口中运行node命令的目录(即您的工作目录).从技术上讲,它从您的工作目录开始,但是可以使用process.chdir()进行更改.

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

例外情况是当您将.require()一起使用时. require中的路径始终相对于包含对require的调用的文件.

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

假设您的目录结构是

/dir1
  /dir2
    pathtest.js

pathtest.js包含

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

你做

cd /dir1/dir2
node pathtest.js

你得到

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

您的工作目录是/dir1/dir2,因此这是.解析的.由于pathtest.js位于/dir1/dir2中,因此__dirname也会解决该问题.

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

但是,如果您从/dir1

cd /dir1
node dir2/pathtest.js

你得到

. = /dir1
__dirname = /dir1/dir2

在这种情况下,您的工作目录为/dir1,因此.可以解决此问题,但是__dirname仍可以解决/dir1/dir2.

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

如果在dir2/pathtest.js内部,您需要进行require调用,以在dir1内部包含文件,您将始终执行

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

因为require中的路径始终相对于您在其中调用它的文件.它与您的工作目录无关.

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

这篇关于node.js中的__dirname和./有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆