What is the difference between path.join and path.resolve?
join just glues segments together with the correct separator. resolve builds an absolute path, processing segments right to left until it has one, and falls back to the current working directory.
Explain it simply
path.join is like writing an address by writing the parts one after the other: "Lane 4, Block B, Sector 5". The result may stay relative. path.resolve behaves like asking, "Starting from where I am standing, what is the full address?" It always gives a full, absolute path.
Example
Assume the current working directory is /home/app.
const path = require("path");
console.log(path.join("src", "index.js"));
// prints: src/index.js
console.log(path.resolve("src", "index.js"));
// prints: /home/app/src/index.js
console.log(path.join("/data", "/reports", "a.txt"));
// prints: /data/reports/a.txt
console.log(path.resolve("/data", "/reports", "a.txt"));
// prints: /reports/a.txtThe last pair is the key difference. resolve works from the right: when it meets a segment that starts with /, it treats that as the root and ignores everything before it. join does not care; it just concatenates and cleans.
Use join to build a path from known pieces. Use resolve when you need an absolute path, for instance to check that a file stays inside a base folder.
What to say in the interview
"join concatenates and normalises; resolve produces an absolute path, and a segment starting with a slash resets it. I use resolve when I need a full path or want to compare against a base directory."
Common mistakes
- Expecting
resolveto keep earlier segments after an absolute one. - Relying on the working directory when you should use
__dirname.