Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative url to absolute url in nodejs

I have url like this:

http://example.com/path/to/css/../../images/test.jpg

which i want to convert to absolute like the following:

http://example.com/path/images/test.jpg

I am looking for a module in Nodejs to do the same. The module, path, does the same thing. but(path.resolve) prepends with the directory path too.

I am looking for something similar, but for urls.

like image 395
Learner Avatar asked Aug 21 '17 13:08

Learner


People also ask

How do you split a URL in node?

You can split the url string using the split() method by specifying a delimiter ( / in your case) and it will return an array.

What is absolute path and relative path in Nodejs?

The difference between relative and absolute paths is that when using relative paths you take as reference the current working directory while with absolute paths you refer to a certain, well known directory.

What is URL explain relative URL and absolute URL?

A URL specifies the location of a target stored on a local or networked computer. The target can be a file, directory, HTML page, image, program, and so on. An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point.


1 Answers

You can use the URL module. https://nodejs.org/docs/latest/api/url.html

const { URL } = require('url');
new URL('path/images/test.jpg', 'http://example.com/')

URL {
  href: 'http://example.com/path/images/test.jpg',
  origin: 'http://example.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  port: '',
  pathname: '/path/images/test.jpg',
  search: '',
  searchParams: URLSearchParams {},
  hash: '' }
like image 127
posit labs Avatar answered Sep 28 '22 06:09

posit labs