URL Base Resolves Relative References

new URL resolves relative references against a base: plain segments replace the tail, .. climbs, and a leading slash restarts from the root.

JavascriptData Fetching

Code

javascriptsnippet
19 lines
// A base URL makes relative references resolvable
const base = 'file:///srv/app/public/';

// Plain segments replace the last path segment of the base
console.log(new URL('logs/app.txt', base));

// '..' climbs and '.' stays — both normalized
console.log(new URL('logs/../assets/logo.svg', base));
console.log(new URL('./index.html', base));

// A leading slash replaces the whole path from the root
console.log(new URL('/health', base));

// Without a base, a relative reference throws
try {
  new URL('logs/app.txt');
} catch (err) {
  console.log('no base:', err instanceof TypeError);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

URL {
  href: 'file:///srv/app/public/logs/app.txt',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/logs/app.txt',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///srv/app/public/assets/logo.svg',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/assets/logo.svg',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///srv/app/public/index.html',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/index.html',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///health',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/health',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
no base: true

Inside the snippet

Demo state sits in top-level bindings: base.

Points of care

  • The package manager never enters the picture for this snippet.

Putting it to use

The demo output is labeled (no base:), so every printed line maps back to its originating operation.

Core lines under the microscope

const base = 'file:///srv/app/public/';
new URL('logs/app.txt');

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `base`.