What is __dirname and __filename in Node.js?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Node.js development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

__dirname is a global variable in Node.js CommonJS modules that contains the absolute directory path of the currently executing module's file. __filename contains the absolute path of the currently executing file, including the filename itself. They are extremely useful for constructing file paths relative to the current module, avoiding issues with the current working directory changing: const configPath = path.join(__dirname, "config", "settings.json");. This is preferable to relative paths like "./config/settings.json", which are resolved relative to process.cwd() (the directory from which Node.js was launched), not the module's location. Note: In ES Modules (.mjs or "type": "module"), __dirname and __filename are not available. The equivalent is: import.meta.url + new URL() + fileURLToPath().

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.