Nodejs Url Module
[Node.js Built-in Modules](#)\n\n* * *\n\nThe `url` module in Node.js is a built-in module used to handle and parse URLs (Uniform Resource Locators). It provides a series of utility methods that make it easy to parse, format, and manipulate URL strings.\n\nA URL (Uniform Resource Locator) is an address used on the internet to identify and locate resources, for example:\n\nhttps://www.example.com:8080/path/to/resource?query=string#hash\n\n* * *\n\n## Core Methods\n\n### url.parse() Method\n\nThe `url.parse()` method is used to parse a URL string into a URL object.\n\n## Example\n\nconst url = require('url');\n\nconst urlString ='https://www.example.com:8080/path/to/resource?query=string#hash';\n\nconst parsedUrl = url.parse(urlString);\n\nconsole.log(parsedUrl);\n\nThe output will contain the following properties:\n\n* `protocol`: Protocol (e.g., 'https:')\n* `host`: Hostname and port (e.g., 'www.example.com:8080')\n* `hostname`: Hostname (e.g., 'www.example.com')\n* `port`: Port number (e.g., '8080')\n* `pathname`: Path portion (e.g., '/path/to/resource')\n* `query`: Query string (e.g., 'query=string')\n* `hash`: Fragment identifier (e.g., '#hash')\n\n### url.format() Method\n\nThe `url.format()` method does the opposite of `parse()`, converting a URL object back into a string.\n\n## Example\n\nconst url = require('url');\n\nconst urlObject ={\n\n protocol:'https:',\n\n host:'www.example.com:8080',\n\n pathname:'/path/to/resource',\n\n query:{ query:'string'},\n\n hash:'#hash'\n\n};\n\nconst formattedUrl = url.format(urlObject);\n\n console.log(formattedUrl);\n\n// Output: https://www.example.com:8080/path/to/resource?query=string#hash\n\n### url.resolve() Method\n\nThe `url.resolve()` method is used to resolve a target URL relative to a base URL.\n\n## Example\n\nconst url = require('url');\n\nconst baseUrl ='https://www.example.com/path/';\n\nconst relativeUrl ='to/resource';\n\nconst resolvedUrl = url.resolve(baseUrl, relativeUrl);\n\n console.log(resolvedUrl);\n\n// Output: https://www.example.com/path/to/resource\n\n* * *\n\n## Structure of a URL Object\n\nA complete URL object typically contains the following properties:\n\n1. **Protocol (protocol)** - e.g., 'http:' or 'https:'\n2. **Authentication (auth)** - Contains username and password\n3. **Host (host)** - Hostname and port number\n4. **Hostname (hostname)** - Hostname only\n5. **Port (port)** - Port number\n6. **Path (pathname)** - Resource path\n7. **Query String (search)** - Query string starting with '?'\n8. **Query Parameters (query)** - Parsed result of the query string\n9. **Fragment Identifier (hash)** - Fragment identifier starting with '#'\n\n* * *\n\n## New URL API\n\nNode.js also provides a new version of the API based on the WHATWG URL standard:\n\n### URL Class\n\n## Example\n\nconst{ URL }= require('url');\n\nconst myUrl =new URL('https://www.example.com:8080/path/to/resource?query=string#hash');\n\nconsole.log(myUrl.protocol);// 'https:'\n\n console.log(myUrl.hostname);// 'www.example.com'\n\n console.log(myUrl.port);// '8080'\n\n console.log(myUrl.pathname);// '/path/to/resource'\n\n console.log(myUrl.search);// '?query=string'\n\n console.log(myUrl.hash);// '#hash'\n\n### URLSearchParams Class\n\n`URLSearchParams` provides convenient methods for handling query strings:\n\n## Example\n\nconst{ URL, URLSearchParams }= require('url');\n\nconst myUrl =new URL('https://example.com/?name=John&age=30');\n\nconst params =new URLSearchParams(myUrl.search);\n\n// Get parameters\n\n console.log(params.get('name'));// 'John'\n\n console.log(params.get('age'));// '30'\n\n// Add parameter\n\n params.append('city','New York');\n\n// Delete parameter\n\n params.delete('age');\n\n// Convert to string\n\n console.log(params.toString());// 'name=John&city=New+York'\n\n* * *\n\n## Practical Application Scenarios\n\n### 1. Parsing Request URLs\n\nParsing client request URLs in an HTTP server:\n\n## Example\n\nconst http = require('http');\n\nconst url = require('url');\n\nconst server = http.createServer((req, res)=>{\n\nconst parsedUrl = url.parse(req.url,true);\n\nconsole.log('Path:', parsedUrl.pathname);\n\n console.log('Query:', parsedUrl.query);\n\nres.end('URL parsed successfully');\n\n});\n\nserver.listen(3000);\n\n### 2. Building API Endpoints\n\nBuilding RESTful API endpoints using the URL module:\n\n## Example\n\nconst http = require('http');\n\nconst url = require('url');\n\nconst server = http.createServer((req, res)=>{\n\nconst parsedUrl = url.parse(req.url,true);\n\nconst path = parsedUrl.pathname;\n\nif(path ==='/api/users'){\n\n// Handle user-related requests\n\n res.end(JSON.stringify({ users:['John','Jane']}));\n\n}else if(path ==='/api/products'){\n\n// Handle product-related requests\n\n res.end(JSON.stringify({ products:['Phone','Laptop']}));\n\n}else{\n\n res.statusCode=404;\n\n res.end('Not Found');\n\n}\n\n});\n\nserver.listen(3000);\n\n### 3. Handling Query Parameters\n\n## Example\n\nconst http = require('http');\n\nconst url = require('url');\n\nconst server = http.createServer((req, res)=>{\n\nconst parsedUrl = url.parse(req.url,true);\n\nconst query = parsedUrl.query;\n\nif(parsedUrl.pathname==='/search'){\n\nconst keyword = query.q||'';\n\nconst page = parseInt(query.page)||1;\n\nres.end(`Searching for"${keyword}" on page ${page}`);\n\n}\n\n});\n\nserver.listen(3000);\n\n* * *\n\n## Best Practices\n\n1. **Always Validate URLs** - Always verify the validity of user-provided URLs before processing them\n2. **Use the New API** - Prefer the WHATWG URL API as it aligns better with modern standards\n3. **Handle Exceptions** - Use try-catch blocks to handle potential errors during URL parsing\n4. **Encode Special Characters** - Use `encodeURIComponent()` to encode special characters in query parameters\n5. **Security Considerations** - When handling redirects, validate the target URL to prevent open redirect vulnerabilities\n\n## Example\n\n// Secure example: Validate redirect URL\n\nfunction isValidRedirect(url){\n\nconst allowedDomains =['example.com','trusted-site.com'];\n\nconst parsedUrl =new URL(url);\n\nreturn allowedDomains.includes(parsedUrl.hostname);\n\n}\n\nBy mastering Node.js's `url` module, you can easily handle various URL-related operations and build more robust and secure web applications.\n\n[Node.js Built-in Modules](#)
YouTip