Node.js url module
In Node.js, theurlmodule is a built-in module used to handle and parse URLs (Uniform Resource Locators). It provides a series of utility methods to easily parse, format, and process URL strings.
URL (Uniform Resource Locator) is an address on the internet used to identify and locate resources, for example:
https://www.example.com:8080/path/to/resource?query=string#hash
Core methods
url.parse() method
url.parse()This method is used to parse a URL string into a URL object.
Example
const urlString = 'https://www.example.com:8080/path/to/resource?query=string#hash';
const parsedUrl = url.parse(urlString);
console.log(parsedUrl);
The output will contain the following properties:
protocol: protocol (e.g., 'https:')host: hostname and port (e.g., 'www.example.com:8080')hostname: hostname (e.g., 'www.example.com')port: port number (e.g., '8080')pathname: path part (e.g., '/path/to/resource')query: query string (e.g., 'query=string')hash: fragment identifier (e.g., '#hash')
url.format() method
url.format()The method, as opposed toparse()Conversely, it converts a URL object into a string form.
Example
const urlObject = {
protocol: 'https:',
host: 'www.example.com:8080',
pathname: '/path/to/resource',
query: { query: 'string' },
hash: '#hash'
};
const formattedUrl = url.format(urlObject);
console.log(formattedUrl);
// Output: https://www.example.com:8080/path/to/resource?query=string#hash
url.resolve() method
url.resolve()This method is used to resolve a target URL relative to a base URL.
Example
const baseUrl = 'https://www.example.com/path/';
const relativeUrl = 'to/resource';
const resolvedUrl = url.resolve(baseUrl, relativeUrl);
console.log(resolvedUrl);
// Output: https://www.example.com/path/to/resource
Structure of the URL object
A complete URL object usually contains the following properties:
- Protocol (protocol)- such as 'http:' or 'https:'
- Authentication information (auth)- contains username and password
- Host (host)- hostname and port number
- Hostname (hostname)- hostname only
- Port (port)- port number
- Path (pathname)- resource path
- Query string (search)- query string starting with '?'
- Query parameters (query)- the parsed result of the query string
- Fragment identifier (hash)- fragment identifier starting with '#'
New URL API
Node.js also provides a new API based on the WHATWG URL standard:
URL class
Example
const myUrl = new URL('https://www.example.com:8080/path/to/resource?query=string#hash');
console.log(myUrl.protocol); // 'https:'
console.log(myUrl.hostname); // 'www.example.com'
console.log(myUrl.port); // '8080'
console.log(myUrl.pathname); // '/path/to/resource'
console.log(myUrl.search); // '?query=string'
console.log(myUrl.hash); // '#hash'
URLSearchParams class
URLSearchParamsProvides convenient methods for handling query strings:
Example
const myUrl = new URL('https://example.com/?name=John&age=30');
const params = new URLSearchParams(myUrl.search);
// Get parameter
console.log(params.get('name')); // 'John'
console.log(params.get('age')); // '30'
// Add parameter
params.append('city', 'New York');
// Delete parameter
params.delete('age');
// Convert to string
console.log(params.toString()); // 'name=John&city=New+York'
Practical application scenarios
1. Parsing request URLs
Parse the URL of a client request in an HTTP server:
Example
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
console.log('Path:', parsedUrl.pathname);
console.log('Query:', parsedUrl.query);
res.end('URL parsed successfully');
});
server.listen(3000);
2. Building API endpoints
Use the URL module to build RESTful API endpoints:
Example
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
if (path === '/api/users') {
// Handle user-related requests
res.end(JSON.stringify({ users: ['John', 'Jane'] }));
} else if (path === '/api/products') {
// Handle product-related requests
res.end(JSON.stringify({ products: ['Phone', 'Laptop'] }));
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000);
3. Handling query parameters
Example
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const query = parsedUrl.query;
if (parsedUrl.pathname === '/search') {
const keyword = query.q || '';
const page = parseInt(query.page) || 1;
res.end(`Searching for "${keyword}" on page ${page}`);
}
});
server.listen(3000);
Best practices
- Always validate URLs- When handling user-provided URLs, always validate their validity
- Use the new API- Prefer the WHATWG URL API, as it is more in line with modern standards
- Handle exceptions- Use try-catch to handle errors that may occur during URL parsing
- Encode special characters- Use
encodeURIComponent()to encode special characters in query parameters - Security considerations- When handling redirects, validate the target URL to prevent open redirect vulnerabilities
Example
function isValidRedirect(url) {
const allowedDomains = ['example.com', 'trusted-site.com'];
const parsedUrl = new URL(url);
return allowedDomains.includes(parsedUrl.hostname);
}
By mastering Node.js'surlmodule, you can easily handle various URL-related operations and build more robust and secure web applications.
Node.js built-in modules