__filename


当前模块的文件名。这是当前模块文件的绝对路径,已解析符号链接。

【The file name of the current module. This is the current module file's absolute path with symlinks resolved.】

对于主程序,这不一定与命令行中使用的文件名相同。

【For a main program this is not necessarily the same as the file name used in the command line.】

有关当前模块的目录名称,请参见 __dirname

【See __dirname for the directory name of the current module.】

示例:

【Examples:】

/Users/mjr 运行 node example.js

【Running node example.js from /Users/mjr

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

给定两个模块:ab,其中 ba 的依赖,并且有如下目录结构:

【Given two modules: a and b, where b is a dependency of a and there is a directory structure of:】

  • /Users/mjr/app/a.js
  • /Users/mjr/app/node_modules/b/b.js

b.js 中引用 __filename 将返回 /Users/mjr/app/node_modules/b/b.js,而在 a.js 中引用 __filename 将返回 /Users/mjr/app/a.js

【References to __filename within b.js will return /Users/mjr/app/node_modules/b/b.js while references to __filename within a.js will return /Users/mjr/app/a.js.】