Home » Node.js

URL (Uniform Resource Locator) module in node.js

In this article, we are going to learn about Uniform resource locator (URL) Module in Node.js.
Submitted by Manu Jemini, on November 17, 2017

We all need Uniform Resource Locator (URL) or a name as a reference for web address that we typed in our local browser to process further and go to a website. URL basically works as a house address and it has some properties of its own.

So, in this tutorial we are going to learn URL module in Node.js.

URL module

URL is a module from node.js, which we used to parse the URL for getting the URL object and each part of address. For parsing the URL we need to require URL module and need to use its .parse() property.

Server file

//step 1
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
//step 2
console.log(q.host);
console.log(q.pathname);
console.log(q.search);
//step 3
var qdata = q.query;
console.log(qdata.month);

Here we have come up with a very fundamental server in express.js.

  • We need to require URL module from node modules and store its reference in variable URL.
  • We store an address in local variable adr.
  • Use .parse() property to parse the URL and pass adr as argument.
  • After that, console.log() host, pathname and search items from address.
  • Now, we use .query() property from our address.
  • Then, we will show month from query data on console.

To run server file, you just need to save it by a random name and then open command, type node and file name.

URL Module in Node.Js

Have fun and do comment if any query.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.