I am getting warnings in VS Code that url.format from the NodeJS URL module is deprecated.
const nodeUrl = require('url')
const url = nodeUrl.format({
protocol: 'https',
host: 'example.com',
pathname: 'somepath'
})
What shall I use instead? Is it fully safe to just replace the above by
const buildUrl = (url) => url.protocol + '://' + url.host + '/' + url.pathname
Are these two functions equivalent, that is, for any object input with that structure, it results in the same output? Doesn't url.format have any magic that I may miss? For example pathname with or without leading /.
My project is huge with a lot of calls to url.format and I want to be sure that nothing breaks.
edit: Apparently we should use WHATWG URL standard
Is then this the correct replacement?
const buildUrl = (url) => new URL(url.pathname, url.protocol + '://' + url.host)
Take a look at the documentation for URL, and be sure to note the differences in certain properties like host (includes port) vs hostname (doesn't). Based on the components in your question, it seems like you need to use a function like the following, which you can extend for your needs:
function urlFromComponents ({pathname = '/', protocol = 'https:', ...props} = {}) {
const url = new URL('https://site.example');
url.protocol = protocol;
url.hostname = props.hostname;
url.pathname = pathname;
return url;
}
const protocol = 'https';
const hostname = 'example.com';
const pathname = 'somepath';
const url1 = urlFromComponents({
hostname,
pathname, // pathname will have "/" prepended if absent
protocol, // protocol actually ends in ":", but this will also be fixed for you
});
const url2 = urlFromComponents({hostname, pathname});
console.log({url1, url2});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With