__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.jsa.js 中的 __filename 会返回 /Users/mjr/app/a.js

The file name of the current module. This is the resolved absolute path of the current module file.

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.