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则是该文件所在目录的绝对路径

转载于:https://www.cnblogs.com/shuizhongyueming/archive/2012/08/08/the-different-between-__filename-__dirname-in-nodeJs.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值