Why use url.parse(req.url).pathname

683 views
Skip to first unread message

Hardik Ruparel

unread,
Apr 26, 2011, 7:03:05 AM4/26/11
to nodejs
In many open source projects, I've seen the following code being used
to extract the requested pathname from URL (eg: to extract /about from
http://example.com/about)

var url = require('url');
...
//after creating server
var path = url.parse(req.url).pathname

But, req.url already contains /about. Why convert it into a URL object
and re-extract the pathname ?

I'm new to Node and it just struck me as something I should get to the
bottom of..
Thanks,

Hardik Ruparel

mscdex

unread,
Apr 26, 2011, 10:50:54 AM4/26/11
to nodejs
On Apr 26, 7:03 am, Hardik Ruparel <hardik...@gmail.com> wrote:
> But, req.url already contains /about. Why convert it into a URL object
> and re-extract the pathname ?

Most likely because other things can exist in the url request, such as
the `search`/`query` portion. Using pathname allows you to easily
disregard that extra information for some urls.

Isaac Schlueter

unread,
Apr 26, 2011, 1:05:28 PM4/26/11
to nod...@googlegroups.com
Yes, mostly it's to discard the query params.

But also, request.url MAY actually contain the whole url. This is
allowed anywhere (though discouraged, and web browsers generally don't
do this) and is required for proxy requests.

Lastly, a request url MAY contain a hash fragment, though curl is the
only browser that I've seen send the hash fragment to the server.
Generally browsers strip it off.

Urls are ugly. You gotta clean em up first.

> --
> You received this message because you are subscribed to the Google Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com.
> To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.
>
>

Hardik Ruparel

unread,
Apr 27, 2011, 3:52:26 AM4/27/11
to nodejs
Thanks guys, that cleared it up !!
Reply all
Reply to author
Forward
0 new messages