Locate module-relative resources
Build a path to a file shipped beside the current CommonJS module.
Node.js · Pipe
__filename is a CommonJS module variable containing the current module’s absolute file path, with symbolic links resolved. It is module-local, not a true global.
In a CommonJS module, __filename is a string containing the absolute path of the current module, with symbolic links resolved. Its value is local to each module rather than a true global, so dependencies see their own file paths.
__filenameA string containing the current CommonJS module's resolved absolute file path.
__filename since version 0.0.1.__dirname when the directory, rather than the full filename, is needed.console.log(__filename);
console.log(__dirname);Run this CommonJS file with Node.js to print its absolute module path and containing directory.
Build a path to a file shipped beside the current CommonJS module.
Log which source file produced a message or error.
Distinguish the paths of an application module and its dependencies.
__filename contain?__filename is a CommonJS-only module variable whose value is the current module's absolute path, with symlinks resolved. It is scoped to the module, so each dependency receives its own filename.
Follow-up: How would you obtain the equivalent in an ES module? Use the ES module URL context, such as import.meta.url, and convert it with the URL and path utilities when a filesystem path is needed.
__filename a global variable?It is not a genuine global. Node.js provides it in the scope of CommonJS modules, alongside variables such as __dirname, exports, module, and require().
Follow-up: Why does this distinction matter? A variable that is module-local cannot be assumed to exist in unrelated module scopes or in the same form under another module system.
__filename?The value depends on the module where the expression appears. If module a loads dependency b, a sees the absolute path to a.js, while b sees the absolute path to b.js.
Follow-up: How can this help locate resources? Resolve a resource relative to the current module's directory rather than relying on the process's current working directory.
__dirnameCommonJS modulesmodulerequire()