Node: `url.format` does not have same behavior for pathnames with and without slashes

Created on 22 Mar 2018  路  6Comments  路  Source: nodejs/node

Using [email protected] on OSX.

Problem

url.format returns an usable result when pathname is not slash prefixed:

> const url = require('url')
> url.format({hostname: 'dougbeck.me', pathname: 'womp.html'})
'dougbeck.mewomp.html'

Expectation

pathname is treated the same with or without the leading / (slash)

Conversation started here: https://github.com/nodejs/help/issues/1176

confirmed-bug url wontfix

All 6 comments

@beck From what I understand looking at the code, adding missing FORWARD_SLASH logic only applies to slashedProtocol like http, https and so on. So if we pass the protocol to format like below it handles it well :

> const url = require('url')
> url.format({protocol: 'http', hostname: 'dougbeck.com', pathname: 'womp.html'})
'http://dougbeck.com/womp.html'

One solution is to take out the logic to add missing FORWARD_SLASH from the slashedProtocol condition and make it generic. I'd like to get more inputs before going ahead with the PR. @addaleax

I'm not sure about this one... There are protocols that don't have slashes before pathname (e.g. mailto). I suppose we could check that hostname & pathname exist but given that the legacy url stuff is meant to be frozen, I don't know how I feel about it.

the legacy url stuff is meant to be frozen

馃憤I'm cool with this being labeled confirmed and wontfix.

If anyone else stumbles upon this, this is the helper I used to give me the API I desired.

@apapirovski @beck : Passing the protocol along is probably the safe thing to do. Given its the legacy stuff, I agree that probably it can be left as is.

Another option is to use slashes:

url.format({ slashes: true, hostname: 'dougbeck.com', pathname: 'womp.html' })

or url.URL as already suggested in https://github.com/nodejs/help/issues/1176.

Closing, let me know if it should stay open.

Was this page helpful?
0 / 5 - 0 ratings