Node.js Url Module

How to use Node.js Url Module to route application using url.pathname

Node.js Url Module is used to split URL into readable parts which can be hostname,pathname etc.Its inbuilt Node.js module.

Including Node.js Url Module

To use url module add below code

http url routing using url.pathname

Below code creates a http server that accepts  http requests and forwards them accordingly.

Open your browser and enter below urls and see the results.

  1. http://localhost:8080/
  2. http://localhost:8080/read
  3. http://localhost:8080/up/update

Splitting url address using url.parse method.

We can use url.parse(address,boolean ) method to retrieve url parts.Example code.


Node.js url module
Node.js url module and parse address method

Serving files using Node.js url module

Previously we learned how to read and write files in Node.js. .We are using to use the same file read methods combined with url parse method to read the url.pathname, determine the file and display it in the browser.

Create two html files.

File number 1. Save it as nodefile.html

File number 2. Save it as javafile.html

Node.js file server code

Its now time to write the node.js file server code that will read the two HTML files and display results.

Save above code as urlmodule.js.Make sure you all save the HTML files in the same folder. Run above code and enter following urls in your browser.




node.js file server
Node.js file serving example




node.js file server

Don’t forget to share this article and leave a comment.