skip to content

In Node.js, how do path.join, path.resolve and path.normalize differ, and how do you check that a computed path stays inside a base directory?

level: middleimportance: should knowfreq 48%

answer

  1. glue versus anchor
  2. an absolute segment resets only one of them
  3. process.cwd() as the fallback
  4. path.relative and a leading ..

basics

~20 s

path.join glues segments and normalises; path.resolve builds an absolute path, restarting at any absolute segment and falling back to process.cwd(); path.normalize only tidies one string. None checks containment: resolve both paths and test path.relative(base, target).

solid answer

~30 s

`path.join(...segments)` concatenates every segment with the platform separator, then normalises, so `path.join('/srv/uploads', '/etc/passwd')` gives `/srv/uploads/etc/passwd`. `path.resolve(...segments)` works right to left until it has an absolute path, so the same call gives `/etc/passwd`, and a relative input is anchored at `process.cwd()`. `path.normalize(p)` just collapses `.`, `..` and repeated separators in one string. All three are string operations, and `..` can climb out of the base: `path.join('/srv/uploads', '../../etc/passwd')` is `/etc/passwd`. To check containment, resolve both paths, take `rel = path.relative(base, target)`, and reject when `rel` is `..`, starts with `..` plus `path.sep`, or is absolute. Never test `target.startsWith(base)`: `/srv/uploads-old` passes it.

code

javascript · 15 lines
javascript
import path from 'node:path';

function resolveInside(baseDir, name) {
  const base = path.resolve(baseDir);
  const target = path.resolve(base, name);
  const rel = path.relative(base, target);
  if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) {
    throw new Error('path escapes the base directory');
  }
  return target;
}

console.log(path.join('/srv/uploads', '/etc/passwd'));    // /srv/uploads/etc/passwd
console.log(path.resolve('/srv/uploads', '/etc/passwd')); // /etc/passwd
console.log(resolveInside('/srv/uploads/u42', 'cv.pdf'));  // /srv/uploads/u42/cv.pdf

go deeper

for a junior

Recall what each function returns for a simple input, and that path.resolve always produces an absolute path while path.join does not.

for a middle

Explain the right-to-left rule of path.resolve, why an absolute later segment resets it but not path.join, and write the path.relative containment check without the startsWith bug.

for a senior

Show where a lexical check stops: symbolic links, process.cwd() surprises in CLIs and Windows drive letters, and choose realpath when the directory can contain links.

for a principal

Decide the team helper: one audited resolveInside function for every path built from input, so containment logic is not reinvented per handler.

## Three string functions with different jobs Node's `node:path` module manipulates **path strings**; it never touches the disk. Three of its functions are easy to confuse because all of them normalise their output. | Function | What it does | `'/srv/uploads'` + `'/etc/passwd'` | Relative input | |---|---|---|---| | `path.join(...paths)` | joins every segment with the separator, then normalises | `/srv/uploads/etc/passwd` | stays relative | | `path.resolve(...paths)` | processes right to left until the result is absolute | `/etc/passwd` | prefixed with `process.cwd()` | | `path.normalize(p)` | collapses `.`, `..` and repeated separators in one string | not applicable | stays relative | Key behaviours, all from the `node:path` reference: - `path.join` ignores zero-length segments and returns `'.'` if everything was empty. - `path.resolve` always returns an **absolute** path and removes a trailing slash unless the result is the root. With no arguments it returns the current working directory. - `path.normalize` **preserves** a trailing separator, and its `..` collapsing is purely textual, so it can disagree with how the operating system would resolve a path that runs through a symbolic link. - All three throw a `TypeError` when given a non-string segment. ## Which one to use 1. **Building a path under a known directory**: `path.join(baseDir, 'avatars', fileName)`. It reads as concatenation and keeps a relative base relative. 2. **Turning user or config input into an absolute path**: `path.resolve(input)`. A CLI flag such as `--out ./dist` should be resolved once against `process.cwd()` so later code does not depend on where it runs. 3. **Cleaning a path you already have**: `path.normalize(p)`, for display or comparison. 4. **Paths relative to a module file**: anchor on `import.meta.dirname` (or `__dirname` in CommonJS), never on `process.cwd()`, which is wherever the process was launched. ## Worked outputs from the reference Reading a few calls closely is the quickest way to internalise the rules (POSIX results): - `path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')` returns `'/foo/bar/baz/asdf'`: the trailing `..` is collapsed by the normalising step. - `path.resolve('/foo/bar', './baz')` returns `'/foo/bar/baz'`, while `path.resolve('/foo/bar', '/tmp/file/')` returns `'/tmp/file'`: the absolute second argument wins and the trailing slash is dropped. - `path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')` is anchored at `process.cwd()`, because no argument is absolute. - `path.normalize('/foo/bar//baz/asdf/quux/..')` returns `'/foo/bar/baz/asdf'`. - `path.join('')` returns `'.'`, and `path.resolve()` with no arguments returns the current working directory. The pattern behind all of them: `join` never discards a segment, `resolve` discards everything to the left of the last absolute one. ## None of them keeps a path inside a directory Every one of these functions honours `..`. In a file-upload service that stores files under `/srv/uploads/<userId>`, a file name that carries `..` segments produces a path outside the user's directory: ```js path.join('/srv/uploads/u42', '../../../etc/passwd'); // '/etc/passwd' ``` Normalising first does not help, because normalising is exactly what turns that string into `/etc/passwd`. `path.isAbsolute` is no guard either: its documentation notes it tests the literal string and is not safe for mitigating path traversals. Why this is an attack class and how to rank the defences belongs to the application-security material; this answer stays with the Node API that performs the check. ## A containment check with node:path The reliable lexical check compares two **resolved** paths with `path.relative`: - Resolve the base once: `const base = path.resolve('/srv/uploads', userId)`. - Resolve the candidate against it: `const target = path.resolve(base, name)`. - Compute `const rel = path.relative(base, target)`. - Reject when `rel === '..'`, when `rel.startsWith('..' + path.sep)`, or when `path.isAbsolute(rel)` (on Windows, a different drive yields an absolute result). - An empty `rel` means the target **is** the base directory; decide whether that is allowed. Two tempting shortcuts are wrong: - `target.startsWith(base)` accepts `/srv/uploads/u42-old/x`, a sibling that merely shares the prefix. - `rel.startsWith('..')` rejects a legitimate file literally named `..notes`. ## What the check does not cover The check is **lexical**. If a symbolic link inside the base points elsewhere, the string looks contained while the file system goes outside. When links can exist under the base, compare `fs.promises.realpath()` of both sides instead. Platform separators matter too: the default `path` follows the host platform, while `path.posix` and `path.win32` force one. On Windows both `/` and `\` separate segments, but the `path` functions only emit `\`.

  • A Node CLI is run from different directories and sometimes cannot find its own template files. What is wrong and how do you fix it?
    It is resolving template paths against `process.cwd()`, which is the directory the user launched it from, through `path.resolve('templates')` or a bare relative `readFile`. Anchor module-relative files on `import.meta.dirname`, or `__dirname` in CommonJS, with `path.join(import.meta.dirname, 'templates', name)`, or pass `new URL('./templates/x', import.meta.url)` to `fs`.
  • When is the path.relative containment check not enough on its own?
    When symbolic links can exist inside the base. The check compares strings, so `base/link/secret` passes even if `link` points outside. Compare `realpath` of both sides, or keep links out of the directory. It also cannot see the file change between check and open, which is a separate race to design around.

  • path.join and path.resolve are interchangeable apart from style
  • path.normalize removes '..' segments, so it makes a user-supplied name safe
  • target.startsWith(base) proves a resolved path is inside base
  • path.resolve with a relative argument resolves against the current module's directory
  • path.isAbsolute(name) being false means the name cannot leave the base directory