Beginner Node.js Interview QuestionsBeginnerConcept
Node.js · Question 22
What are __dirname and __filename in Node.js?
Direct answer
__filename is the absolute path of the current module file; __dirname is its directory — CommonJS globals for resolving relative paths; in ESM use import.meta.url with fileURLToPath instead.
Before ESM, __dirname was the standard way to load config.json next to your script regardless of cwd. import.meta.url is the ESM equivalent tied to the module URL.
| CommonJS | ESM | |
|---|---|---|
| File path | __filename | fileURLToPath(import.meta.url) |
| Directory | __dirname | path.dirname(fileURLToPath(import.meta.url)) |
| Available | In .cjs / type absent | Not defined — use meta.url pattern |
- cwd vs __dirname — process.cwd() changes if user cd's before node; __dirname always follows the file location.
- path.join — join(__dirname, 'data', 'file.json') avoids manual slash bugs (Q24).
- Bundlers — may rewrite paths at build time; server runtime uses real filesystem paths.
dirname-esm.mjs
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const configPath = path.join(__dirname, "config", "default.json");
console.log(configPath);