CodePark/ questions / File system & path
START PRACTICINGPRACTICE
Backend question · Node.js › File system & path

On Linux, what does this log?

const path = require("node:path");
console.log(path.join("/a", "b", "../c"));
console.log(path.resolve("/a", "/b", "c"));
/a/c and /b/c

The output is /a/c and /b/c.

path.join joins the segments and then normalizes the result. Normalizing removes .. and . parts. So b/.. cancels out, and you get /a/c.

path.resolve works through the segments from right to left. It stops as soon as it has an absolute path, meaning a path that starts with /. Here, /b is absolute, so resolve ignores /a and you get /b/c. If no segment is absolute, resolve adds process.cwd() (the current working directory) at the start.

That is why "/a/c and /a/b/c" is wrong:
resolve does not keep /a once it meets the absolute /b.