Node.js
URL.resolve
Learn to resolve relative URLs with URL.resolve.
Resolving relative URLs
When a page has a relative link like "/sub", the browser turns it into a full address. This is called URL resolution. In Node.js you do it with new URL(relative, base).
Example: new URL("sub", "https://example.com/main") gives https://example.com/sub. new URL("../sibling", "https://example.com/a/b/c") gives https://example.com/a/sibling. base is the second parameter; the relative path is resolved against it. Older Node.js versions had a url.resolve(base, relative) function; it has been removed. In new code always use new URL(relative, base). This is useful for crawling relative links on a page or building endpoints from an API base.
Base and relative interaction
The result of resolution comes from the relative path replacing the last path component of the base. "./" means the same directory, "../" the parent, "/" the root.
Examples: new URL("./x", "https://example.com/a/b") → https://example.com/a/x; new URL("../x", "https://example.com/a/b") → https://example.com/x; new URL("/x", "https://example.com/a/b") → https://example.com/x. If the relative path contains a protocol like https://, the base is ignored; the absolute URL is used directly. This matches the <a href> logic in browsers. Resolving all links of a site from a single base keeps behavior consistent.
Exercise Resolve a relative URL
Define const base = "https://example.com/ana/sayfa";. Resolve with const resolved = new URL("alt", base);. Print with console.log(resolved.href).
Show example solution
const base = "https://example.com/ana/sayfa";
const resolved = new URL("alt", base);
console.log(resolved.href);
Test yourself
-
What is the modern way to resolve a relative URL?
new URL("alt", "https://example.com/ana")
- new URL(relative, base)
- url.resolve(base, rel)
- url.parse(rel)
- path.join(base, rel)
Show answer
new URL(relative, base) — new URL(relative, base) is the modern and recommended way.
-
Match each relative path to its meaning
- ./x
- Same directory
- ../x
- Parent directory
- /x
- Root directory
- https://...
- Absolute (base ignored)
-
Complete the resolution call
const resolved = new URL(____, base);
Show answer
const resolved = new URL("alt", base);
Next lesson: querystring