Nearby lessons
12 of 21🌐 URL Module in Node.js
📌 What is URL?
What is a URL?
- A URL (Uniform Resource Locator) is the address of a unique resource on the internet.
- It is used by browsers to retrieve resources such as HTML pages, CSS files, images, etc.
- Each valid URL points to a unique resource.
Hash Sign and Fragment
- A hash sign (
#) in a URL is referred to as a fragment. - URL fragments historically set the browser's scroll position to a predefined location on a page.
- If a URL refers to a document, the fragment refers to a specific subsection.
The Built-in URL Module in Node.js
- The URL module splits a web address into readable parts.
- It provides utilities for parsing and resolving URLs.
- Parsing converts an unstructured string into a structured object that's easier to work with.
📝 Example 1 - Parse a Static URL
Node.js Environment
RUNTIME ACTIVE
const url = require('url'); // Static URL var addr = 'https://www.example.com/category/search?name=CodingsPoints&age=50#section1'; const myURL = url.parse(addr, true); console.log(myURL);
Terminal Output
📝 Example 2 - Access URL Parts
Node.js Environment
RUNTIME ACTIVE
const url = require('url'); // Static URL var addr = 'https://www.example.com/category/search?name=CodingsPoints&age=50#section1'; const myURL = url.parse(addr, true); console.log(myURL.protocol); console.log(myURL.host); console.log(myURL.hash); console.log(myURL.search); console.log(myURL.pathname);
Terminal Output
📝 Example 3 - Log Request URL in Server
Node.js Environment
RUNTIME ACTIVE
const url = require('url'); const http = require('http'); http.createServer((req, res) => { res.write('Response From Server..Codings Points'); console.log(req.url); res.end(); }).listen(3000, "localhost", () => { console.log("Server Running At http://localhost:3000"); });
Terminal Output
📝 Example 4 - Parse Request URL in Server
Node.js Environment
RUNTIME ACTIVE
const url = require('url'); const http = require('http'); http.createServer((req, res) => { const myURL = url.parse(req.url, true); res.write('Response From Server..Codings Points'); console.log(myURL.search); console.log(myURL.pathname); res.end(); }).listen(3000, "localhost", () => { console.log("Server Running At http://localhost:3000"); });
Terminal Output
Keep Going!Routing in Node.js