Skip to content

Path.relativeTo property

pathlib-ts > Path > relativeTo

Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.

Signature:

relativeTo: PathRelativeToFn;

The *walkUp* parameter controls whether .. may be used to resolve the path.

  • "parent" — do not touch the filesystem, always anchor at other.parent. - "exact" — unchanged CPython semantics (default). - "auto" — uses stat/lstat under the hoodset extra.followSymlinks to control how symlinks are treated.

By default the method behaves like CPython (policy: "exact"). Specify options.extra.policy to opt into import-friendly behaviour ("auto") or a lexical parent anchor ("parent"). When policy === "auto" the operation may consult the filesystem and therefore returns a promise. See docs/caveats.md for nuance around symlinks and module resolution.

Relative path for colocated assets while mirroring JS module semantics

const asset = new Path("/src/assets/img.webp");
const content = new Path("/src/foo/bar/content.mdx");
const relative = await asset.relativeTo(content, {
walkUp: true,
extra: { policy: "auto" }
});
console.log(relative.toString()); // '../../assets/img.webp'