nodejs中的__filename与__dirname具体示例及区别讲解
__filename指的是文件的绝对路径;
__dirname指的是文件所在的目录的绝对路径;
具体示例如下:
a,js
var test2=require("./b.js");
console.log('a.js filenameis '+__filename);
console.log('a.js dirname is '+__dirname);
b.js
console.log('b.js filenameis '+__filename);
console.log('b.js dirname is '+__dirname);
a.js和b.js处于同级目录,运行结果为:
b.js filenameis c:\users\administrator\desktop\winter\b.js
b.js:1
b.js dirname is c:\users\administrator\desktop\winter
b.js:2
a.js filenameis c:\users\administrator\desktop\winter\a.js
a.js:2
a.js dirname is c:\users\administrator\desktop\winter
a.js:3
a.js改为
var test2=require("./subdir/b.js");
console.log('a.js filenameis '+__filename);
console.log('a.js dirname is '+__dirname);
b.js不变
运行结果为:
b.js filenameis c:\users\administrator\desktop\winter\subdir\b.js
b.js:1
b.js dirname is c:\users\administrator\desktop\winter\subdir
b.js:2
a.js filenameis c:\users\administrator\desktop\winter\a.js
a.js:2
a.js dirname is c:\users\administrator\desktop\winter
a.js:3
所以,都是绝对路径,看需要的是带文件名的还是只要目录