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.
import path from "node:path"; path.join("data", "users", "ann.json"); // "data/users/ann.json"
Try it
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.
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
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, usepath.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.joinis not a security check.path.join(baseDir, userInput)can still point outsidebaseDirwhen the input contains... See Path traversal.- Prefer
joinover 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.joinfollows the current platform. Usepath.posix.joinfor 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 theURLclass for web addresses.