Question presented to candidate: "You see code building a file path with string concatenation, like folder + '/' + filename. What can actually go wrong with that, and what does Node's path module do differently?"
What a strong answer should cover:
- Node's built-in
pathmodule builds and manipulates file-system paths correctly for the current operating system —path.join,path.resolve,path.basename,path.extname,path.dirname, and others. - 📌 The concrete bug manual concatenation introduces: joining path segments with a hardcoded
"/"(or worse, no separator handling at all) produces double separators, missing separators, or wrong separators entirely depending on whether the input already ended in a slash and which OS is running —path.joinnormalizes all of that automatically. path.joinalso correctly resolves relative segments like".."and"."within the joined result, which naive concatenation does not do at all — it just concatenates literal strings.- Windows uses
\as its separator; POSIX systems (Linux, macOS) use/. Code that hardcodes either separator breaks on the other platform;path.join/path.resolveusepath.sep, the correct separator for the platform actually running, automatically. path.win32andpath.posixare explicitly available for code that needs to build a path for a specific platform regardless of which OS it currently runs on (e.g. generating a path string to embed in a config file meant for a different target platform) — distinct from the defaultpathexport, which always reflects the current platform.- A precise answer distinguishes
path.join(concatenates segments, normalizes the result, does not resolve to an absolute path unless an input already was) frompath.resolve(always produces an absolute path, resolving againstprocess.cwd()if needed) — a commonly confused pair.
Clarifying questions expected:
- "Does this code need to run correctly on both Windows and POSIX, or only one target platform?" — decides how much of the separator discussion actually matters.
- "Is an absolute path needed, or just a correctly joined relative one?" — decides between
path.joinandpath.resolve.
Code / implementation expected: Yes — showing path.join correctly normalizing a case where manual concatenation visibly breaks is the concrete, convincing part of the answer.