nodejs中__filename和__dirname的区别


  在Node-API里面对二者的解释是:

__filename 

 

The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

Example: running node example.js from /Users/mjr

console.log(__filename);
// /Users/mjr/example.js

__filename isn't actually a global but rather local to each module.

 

__dirname 

 

The name of the directory that the currently executing script resides in.

Example: running node example.js from /Users/mjr

console.log(__dirname);
// /Users/mjr

__dirname isn't actually a global but rather local to each module.

  这大概的意思就是,__filename指的是当前解析文件的实际物理地址,而__dirname指的是此文件在被执行时所在的地址

 

   具体的可以通过下面两个代码来看

  test.js

1 var text = require("./test2");
2 console.log("the test.js's filename is: %s",__filename);
3 console.log("the test.js's dirname is %s",__dirname);
4 text.start();

  test2.js

1 function start(){
2     console.log("the test2.js's filename is: %s",__filename);
3     console.log("the test2.js's dirname is %s",__dirname);
4 }
5 exports.start = start;

在这里,test.js  require了 test2.js,二者是在同一个目录下面

然后我们执行node test.js

结果是:

the test.js's filename is: /home/xing/ANodeJsWebSite/node/test.js
the test.js's dirname is /home/xing/ANodeJsWebSite/node
the test2.js's filename is: /home/xing/ANodeJsWebSite/node/test2.js
the test2.js's dirname is /home/xing/ANodeJsWebSite/node

然后我们把test2.js移到上层目录,更改一下test.js里面的require地址,再运行test.js

the test.js's filename is: /home/xing/ANodeJsWebSite/node/test.js
the test.js's dirname is /home/xing/ANodeJsWebSite/node
the test2.js's filename is: /home/xing/ANodeJsWebSite/test2.js
the test2.js's dirname is /home/xing/ANodeJsWebSite

可见__filename始终是用绝对路径显示一个文件的位置,而__dirname则是该文件所在目录的绝对路径


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM