Node.js Reference ยท path, os and url
Node.js path.relative() method
Reference for path.relative() in Node.js: compute how to get from one path to another, how it resolves inputs first, and how to test whether a path is inside a folder.
path.relative(from, to) returns the relative path that leads from from to to. Think of it as the answer to "I am standing in from; which cd do I type to get to to?".
Both arguments are first resolved to absolute paths, as path.resolve() would do, so relative inputs are measured against the current directory. The function never touches the disk.
import path from "node:path"; path.relative("/srv/app", "/srv/data/users"); // "../data/users"
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.relative(from, to): string
| Name | Description |
|---|---|
from |
The starting path. Relative values are resolved against the working directory. |
to |
The destination path. Resolved the same way. |
Returns: the relative path from from to to, using the platform's separator. It is an empty string when both resolve to the same path.
Errors: ERR_INVALID_ARG_TYPE if either argument is not a string.
Usage notes
- Inputs are resolved first.
path.relative("a", "b")depends onprocess.cwd()becauseaandbbecome absolute. Pass absolute paths for predictable results. - Equal paths give
"", not".". Check for the empty string explicitly. - It is the inverse of
join.path.resolve(from, path.relative(from, to))equalspath.resolve(to). - Folder test: a
tothat is insidefromgives a result that does not start with... The simplestartsWith("..")test would also reject a file literally named..data, so a stricter check isrel === ".." || rel.startsWith(".." + path.sep). - Windows drives: with different drives (
C:andD:) there is no relative route, and the function returns the resolvedtopath. - Comparison is case-insensitive on Windows and case-sensitive elsewhere.
- Typical use: show short paths in logs and build tools (
path.relative(process.cwd(), file)), compute import specifiers, or generate links between generated files.