path.resolve vs path.join
nuance of path construction.
join concatenates and normalizes relative segments, resolve builds an absolute path right to left from cwd and resets on any absolute segment.
treating them as interchangeable.
WHAT THIS TESTS This probes subtle but important differences between two heavily used path functions. Misusing them causes files to be read from the wrong directory, a classic source of works-on-my-machine bugs.
A GOOD ANSWER COVERS path.join takes the given segments, joins them with the platform separator, and normalizes the result, collapsing redundant slashes and resolving . and .. segments. If all inputs are relative, the output stays relative. path.resolve instead computes an absolute path. It processes arguments from right to left, prepending segments until it has an absolute path, defaulting to the process current working directory if none of the inputs are absolute. Crucially, if any segment is itself an absolute path, resolve discards everything to its left and restarts from that segment. So resolve is about producing a definitive absolute location, while join is about stitching fragments together.
COMMON WRONG ANSWERS Saying both always return identical strings. Claiming join also consults the current working directory, which it does not. Forgetting that an absolute segment resets resolve's accumulation.
LIKELY FOLLOW-UPS What does path.normalize do compared to these. When is __dirname preferable to relying on cwd. How does an absolute segment behave inside join.
ONE CONCRETE EXAMPLE Given inputs '/foo', 'bar', '/baz', 'qux': path.join('/foo', 'bar', '/baz', 'qux') returns '/foo/bar/baz/qux', simply concatenating and normalizing. path.resolve('/foo', 'bar', '/baz', 'qux') returns '/baz/qux', because the later absolute segment /baz discards the earlier /foo/bar. This divergence is exactly why you cannot treat the two as interchangeable.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.