a blog for those who code

Saturday 29 November 2014

How to parse URL's in Nodejs

In this post we will show you how to parse URLs in your Nodejs HTTP server applications. This is very important because to get authorization, host-name or anything which a URL can give is useful in web applications. Node.js comes with the URL module which you can use to parse the URL's.

Before going into the code let us see what property of an URL does URL module provides us with.

.auth : It provides us with authorization portion of the URL.
.href : It gives us the full URL.
.hash : It gives us the fragment that is present in the URL.
.host : It provides us the full hostname and port of the URL
.hostname : It gives us full name of the host in the URL.
.path : It gives us the pathname.
.pathname : It gives us pathname, hostname and port of the URL.
.port : It gives us the port specified in the URL.
.protocol : It gives us the protocol of the Request.
.search : It gives us the query string of the URL.


var url = require('url');
var urlValue = 'http://localhost:8080/test1/test2?query=value';

var parsedUrl = url.parse(urlValue, true, true);

console.log('Authorization is : ',parsedUrl.auth);
console.log('Href is : ',parsedUrl.href);
console.log('Hash is : ',parsedUrl.hash);
console.log('Hostname is : ',parsedUrl.hostname);
console.log('Path is : ',parsedUrl.path);
console.log('Pathname is : ',parsedUrl.pathname);
console.log('Port is : ',parsedUrl.port);
console.log('Protocol is : ',parsedUrl.protocol);
console.log('Search is : ',parsedUrl.search);
console.log('Slashes is : ',parsedUrl.slashes);

Output : 

If you are working with a parsed URL, and would like to turn that object back into a proper URL, you can use url.format() function on that object. This will re format the object excluding the href back to a URL.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful

No comments:

Post a Comment