__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.