Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js path.join() method

Reference for path.join() in Node.js: combine path segments with the right separator, collapse . and .. parts, and learn how it differs from path.resolve().

path.join() glues path segments together with the platform's separator and then normalizes the result: doubled separators collapse and . and .. segments are resolved. It never touches the disk and it never looks at the current directory, so the result is relative if the first segment is.

Use it whenever you build a path from pieces. It replaces string concatenation, which breaks on doubled slashes and on Windows.

NODE
import path from "node:path";

path.join("data", "users", "ann.json");   // "data/users/ann.json"

Try it

Node.js Joining and normalizing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js join versus resolve, and bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
path.join([...paths]): string
Name Description
...paths Zero or more path segments. Each must be a string. Empty strings are ignored.

Returns: the joined and normalized path. With no arguments, or only empty strings, it returns ".".

Errors: ERR_INVALID_ARG_TYPE if any segment is not a string.

Usage notes

  • Absolute later segments are not special. path.join("/base", "/etc/passwd") is /base/etc/passwd. If you want a later absolute segment to win, use path.resolve().
  • A trailing separator is kept. path.join("docs", "guide/") ends with /. This matters when you compare strings or build URLs.
  • .. cannot climb above the root of an absolute path (/.. is /), but a relative path keeps leading .. segments.
  • join is not a security check. path.join(baseDir, userInput) can still point outside baseDir when the input contains ... See Path traversal.
  • Prefer join over template strings like `${dir}/${name}`. It handles separators, doubled slashes and . segments for you.
  • Pure string work. The path does not need to exist and symbolic links are not resolved. Use fs.realpath() for that.
  • Platform behavior: path.join follows the current platform. Use path.posix.join for URL-like paths (/) on every platform. See path.posix and path.win32.
  • Not for URLs. path.join("http://a.com", "b") collapses the double slash. Use the URL class for web addresses.