__filename


当前模块的文件名。 这是当前的模块文件的绝对路径(符号链接会被解析)。

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

有关当前模块的目录名,参阅 __dirname

示例:

从 /Users/mjr 运行 node example.js

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

给定两个模块:a 和 b,其中 ba 的依赖文件,且目录结构如下:

  • /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

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.

See __dirname for the directory name of the current module.

Examples:

Running node example.js from /Users/mjr

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

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

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.