__filename


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

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

当前模块的目录名见 __dirname

示例:

/Users/mjr 运行 node example.js

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

给定两个模块:ab,其中 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.