Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why use path.join instead of joining file paths with plus signs?

SHORT ANSWER

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

js
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:

js
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.join and exposing files outside the upload folder.

#nodejs#path#fs

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.