Skip to content
Tutorials Center
My learning

Topics

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.

NODE
import path from "node:path";

path.relative("/srv/app", "/srv/data/users");   // "../data/users"

Try it

Node.js Going down, up and sideways

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 Testing whether a path is inside a folder

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.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 on process.cwd() because a and b become 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)) equals path.resolve(to).
  • Folder test: a to that is inside from gives a result that does not start with ... The simple startsWith("..") test would also reject a file literally named ..data, so a stricter check is rel === ".." || rel.startsWith(".." + path.sep).
  • Windows drives: with different drives (C: and D:) there is no relative route, and the function returns the resolved to path.
  • 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.