Back to results for “File System (fs) Module”
Node.js › Path & OS Modules

What is the difference between path.join() and path.resolve(), and when would you use each?

Beginner

Answer

path.join() concatenates path segments together and normalizes the result (resolving '..' and '.' segments), but doesn't guarantee an absolute path -- if all inputs are relative, the result stays relative. path.resolve() processes segments right-to-left, treating them as if changing directories, and always returns an absolute path, using the current working directory as the base if no absolute segment is encountered -- resolve() is typically used when you specifically need a guaranteed absolute path, while join() is used simply to combine path pieces correctly regardless of whether the result ends up absolute or relative.
const path = require('node:path');

path.join('users', 'alice', 'file.txt'); // 'users/alice/file.txt' -- relative, as given
path.resolve('users', 'alice', 'file.txt'); // '/current/working/dir/users/alice/file.txt' -- always absolute
Real-world example A file-loading utility uses path.resolve() rather than path.join() specifically because it needs to guarantee an absolute path is passed to fs.readFile(), regardless of what working directory the script happens to be executed from, avoiding subtle bugs that would occur if a relative path were resolved against an unexpected directory.

Common follow-ups: What happens if path.resolve() is given an already-absolute path as one of its arguments partway through?;How does path.join() specifically handle redundant separators or '..' segments within its inputs?