The double underscores in __dirname
looks intimidating but it’s not! It’s a useful variable that’s been around since the beginnging of the NodeJS project. Why’s it such a core feature of Node.js? __dirname
tells you the absolute path of the directory containing the currently executing file.
__dirname
的双下划线看起来令人生畏,但事实并非如此! 自从NodeJS项目开始以来,这是一个有用的变量。 为什么它具有Node.js的核心功能? __dirname
告诉您包含当前执行文件的目录的绝对路径 。
Here’s a simple example:
这是一个简单的例子:
gator-app
├──index.js
├──public
├──src
│ ├──helpers.js
│ └──api
│ └──crocodile.js
├──cronjobs
│ ├──swamp-pix
│ └──get-latest-gators.js
└──package.json
console.log(__dirname) // "/Users/Sam/gator-app/src/api"
console.log(process.cwd()) // "/Users/Sam/gator-app"
console.log(__dirname) // "/Users/Sam/gator-app/cronjobs"
console.log(process.cwd()) // "/Users/Sam/gator-app"
If you noticed, __dirname
has a different value depending on which file you invoked it in, whereas process.cwd()
(another popular Node.js utility) is different. It always returns the same value: the absolute path of where you started the Node.js process (eg., $ node index.js
).
如果您注意到了, __dirname
根据在哪个文件中调用它而具有不同的值,而process.cwd()
(另一个流行的Node.js实用程序)则不同。 它始终返回相同的值: 在其中启动Node.js进程的绝对路径(例如$ node index.js
) 。
我什么时候应该使用它? (When Should I Use It?)
__dirname
is useful when you want to know the immediate containing folder. You may want to get this path for several reasons:
当您想知道直接包含的文件夹时, __dirname
很有用。 您可能出于以下几个原因而希望获得此路径:
制作新目录 (Making new directories)
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/swamp-pix');
fs.mkdirSync(dirPath); // sibling directory was created named "swamp-pix"
指向目录 (Pointing to directories)
express.static(path.join(__dirname, '/public'));
将文件添加到目录 (Adding files to a directory)
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/swamp-pix/bayou.jpeg');
fs.openSync(filePath, 'a'); // creates file if it doesn't exist
Once you get familiar with Node.js, interacting with your filesystem is easy when you use __dirname
.
一旦熟悉Node.js,使用__dirname
轻松与文件系统进行交互。
Plus, __dirname
is a global object that’s available to use in all your Node.js modules, without having to import anything. That’s because Node modules get wrapped when executed and given access to a series of global objects.
另外, __dirname
是一个全局对象,可以在所有Node.js模块中使用,而无需导入任何内容。 这是因为Node模块在执行并获得对一系列全局对象的访问权时会被包装 。
翻译自: https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname