Why use path.join instead of joining file paths with plus signs?
path.join uses the correct separator for the operating system, normalises extra slashes and dot segments, and avoids missing or doubled slashes, so paths work on Windows, Linux and macOS.
Explain it simply
Windows writes C:\project\uploads\photo.png; Linux writes /home/app/uploads/photo.png. If you build paths by gluing strings with "/" or "\\", your code works on your laptop and breaks on the server. path.join is a helper that knows the local convention and tidies the result.
Example
const path = require("path");
console.log(path.join("uploads", "2026", "photo.png"));
// prints: uploads/2026/photo.png (uploads\2026\photo.png on Windows)
console.log(path.join("uploads/", "/photo.png"));
// prints: uploads/photo.png (no double slash)
console.log(path.join("a", "b", "..", "c"));
// prints: a/c (the .. step is resolved)Other helpers in the same module:
path.basename("/data/report.pdf"); // "report.pdf"
path.extname("/data/report.pdf"); // ".pdf"
path.dirname("/data/report.pdf"); // "/data"Be careful when the second argument comes from a user: path.join(base, userInput) still lets ../../etc/passwd climb out of the folder. Validate or resolve and check the result starts with your base directory.
What to say in the interview
"path.join builds paths portably, handling separators and dot segments. I never concatenate strings for paths, and I validate user-supplied parts to prevent path traversal."
Common mistakes
- Hard-coding backslashes or forward slashes.
- Trusting user input inside
path.joinand exposing files outside the upload folder.