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