Working with URL module in NodeJs

Working with URL module in NodeJs

K. M. Shawkat Zamil | September 25, 2022

Hello Developers,

In this demonstration, I will try to discuss the URL module in NodeJs. Every URL has its own parts. We will discuss this briefly. Let's look into the below URL


Let's dive into the URL -> This part is the host name

test.html -> This part is the path of the URL

?title=Hello&sub-title=World -> This part is the query of the URL


Now see all the things in the code

First, we need to create a server, that's why we need the HTTP module. After that, we need to call the URL module. A method named URL.Parse() wiill be called and we have to pass the URL in the URL.parse() . This method will turn the URL into an object.


By that object, we can get the hostname, path name, and query of the URL. The source code is given below:


var http = require('http');
var URL = require('url');

var server = http.createServer(function (request, response) { 
    var myURL = "";

    var obj = URL.parse(myURL, true);

    var myServerName =;
    var myPathName = obj.path;
    var mySearchQuery =;

    response.writeHead(200, { 'Content-Type': 'text/html' });
    // response.write(myPathName);
    // response.write(mySearchQuery);

console.log('Server Running Successfully');


Just open the comment line to see the result. Then run the below command in the terminal:


node main.js


Hope this might help you in your journey of development.


Read More: How to work with Request and Response in NodeJs


K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.