Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Node.js · Pipe

__filename

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

Since
v0.0.1

How it works

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.

Syntax

__filename

Returns

A string containing the current CommonJS module's resolved absolute file path.

Key points

  • Node.js has provided __filename since version 0.0.1.
  • It identifies the module containing the reference.
  • The returned path is absolute and reflects symlink resolution.
  • Use __dirname when the directory, rather than the full filename, is needed.
  • Node.js documents these CommonJS-specific variables as available within modules.

Common mistakes

  • When the entry file is launched through a command, its resolved path can differ from the path text supplied to Node.js.

Example: Print module location

console.log(__filename);
console.log(__dirname);

Run this CommonJS file with Node.js to print its absolute module path and containing directory.

When to use it

Locate module-relative resources

Build a path to a file shipped beside the current CommonJS module.

Identify the executing module

Log which source file produced a message or error.

Inspect dependency locations

Distinguish the paths of an application module and its dependencies.

Interview questions

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

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

QWhat happens when different CommonJS modules read __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.

  • __dirname
  • CommonJS modules
  • module
  • require()

Source: Modules: CommonJS modules | Node.js v26.11.1 Documentation. Checked 2026-10-15.