Question presented to candidate: "Your code does fs.readFileSync('./config.json') and it works when you run it from the project root, but breaks when a teammate runs it from a different directory. What went wrong, and what should you have used instead?"
What a strong answer should cover:
__dirnameand__filenameare two of the five parameters supplied by Node's implicit CommonJS module wrapper — the current module file's absolute directory path and absolute file path, respectively.- 📌 The bug they fix: a relative path like
./config.jsonis resolved against the process's current working directory (wherever thenodecommand was actually invoked from), not against the file's own location.path.join(__dirname, "config.json")is resolved against the file's own location, which is what most code actually means when it says "the config file next to me." __dirname/__filenameexist only in CommonJS files — in an ES Module, there is no such implicit variable; the equivalent is derived fromimport.meta.url(typically viafileURLToPath(import.meta.url)andpath.dirname(...)of that).- Running code with
node -e "..."or via the REPL produces misleading placeholder values for these (.and[eval]) rather than a real path — a good answer notes this rather than testing/demonstrating the concept that way and drawing the wrong conclusion from it. process.cwd()is the commonly confused alternative — it returns the current working directory of the process, which changes based on how and from where the script was launched, and is a fundamentally different, session-dependent value from a file's own fixed location.- A precise answer names the practical rule: any path meant to be relative to the source file itself (a config file shipped next to the code, a template, a static asset) should be built with
__dirname/import.meta.url, never a bare relative string — those are the correct tool only for a path meant to be relative to wherever the process happens to be invoked from.
Clarifying questions expected:
- "Is this CommonJS or an ES Module?" — the mechanism (implicit variable vs.
import.meta.url) differs. - "Does the path actually need to be relative to the invoking directory, or to the source file?" — this is the real distinction the bug in the prompt is about.
Code / implementation expected: Yes — showing the actual absolute values from a real file, and the ESM equivalent via import.meta.url, is the concrete deliverable.