const { URL } = require('url');
const base = new URL('https://example.com/folder/page.html');
const relative = new URL('../image.png', base);
console.log(relative.href);The relative URL '../image.png' moves one directory up from 'folder/', so the resolved URL is 'https://example.com/image.png'.
const { URL } = require('url');
const base = new URL('https://example.com/folder/page.html');
const absolute = new URL('https://other.com/path', base);
console.log(absolute.href);When the URL constructor receives an absolute URL as the first argument, it ignores the base URL and uses the absolute URL as is.
const { URL } = require('url');
const base1 = new URL('https://example.com/folder/');
const base2 = new URL('https://example.com/folder');
const relative = 'page.html';
console.log(new URL(relative, base1).href);
console.log(new URL(relative, base2).href);When the base URL ends with a slash, the relative URL appends inside that folder. Without the slash, the last part is treated as a file and replaced by the relative URL.
Port numbers must be numeric and within valid range. 'invalid' is not a number, so it causes a SyntaxError.
const { URL } = require('url');
const base = new URL('https://example.com/folder/page.html');
const relative = new URL('subfolder/../image.png', base);
console.log(relative.href);The '..' moves up one directory from 'folder/', so 'subfolder/../image.png' resolves to 'folder/image.png'. The URL class normalizes the path automatically.
