Node.js URL Module

Node.js URL Module

URL Module is used to parse an address into host, pathname, search and query string.

parse method of URL module is used to get url properties.

Syntax :

<%

var url = require('url');

 url.parse();

%>

Parsing a URL using url.parse()

Example :

var url = require('url');
var student = 'http://localhost:5555/getData.html?city=ahmedabad&country=india';
var data = url.parse(student, true);

console.log(data.host); //returns 'localhost:5555'
console.log(data.pathname); //returns '/getData.html'
console.log(data.search); //returns '?city=ahmedabad&country=india'

var objdata = data.query; //returns an object: { city: ahmedabad, country: 'india' }
console.log(objdata.country); //returns 'india'
 

Using URL Constructor (Modern Approach)

Since Node.js v7+, you should use the URL class instead of url.parse().

const { URL } = require('url');

const myUrl = new URL('https://example.com:8080/path/page?name=John Doe&age=80');

console.log('Protocol:', myUrl.protocol);
console.log('Host:', myUrl.host);
console.log('Pathname:', myUrl.pathname);
console.log('Search Params:', myUrl.searchParams);
console.log('Get Query Parameter (name):', myUrl.searchParams.get('name'));

Output : 

Protocol: https:
Host: example.com:8080
Pathname: /path/page
Search Params: URLSearchParams { 'name' => 'John', 'age' => '80' }
Get Query Parameter (name): John Doe
 

Formatting a URL using url.format()
 

Converts an object into a URL string.
const url = require('url');

const urlObject = {
    protocol: 'http',
    host: 'localhost',
    pathname: '/page',
    query: { name: 'John', age: '70' }
};

const formattedUrl = url.format(urlObject);
console.log(formattedUrl);
 

Output : 

http://localhost/page?name=John&age=70
 

Creating a Simple HTTP Server with URL Parsing

Example:

const http = require('http');
const { URL } = require('url');

const server = http.createServer((req, res) => {
    const myUrl = new URL(req.url, `http://${req.headers.host}`);

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('\nPathname: '+myUrl.pathname);
    res.write('\nQuery Parameters: '+myUrl.searchParams);
    var searchArr = myUrl.searchParams;
    searchArr.forEach((value, key) => {
        res.write('\n'+key+':'+value);
    });
    res.end();
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});


Now visit => http://localhost:3000/contactus/address?q=ahmedabad&state=gujarat
It will display:

Pathname: /contactus/address
Query Parameters: q=ahmedabad&state=gujarat
q:ahmedabad
state:gujarat

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

25920