Node.js URL Module
A URL is a web address, such as a street address for a website. The URL module helps your program read each part of an address and build new addresses safely. Web apps use it to read search words, page paths, and website names.
Parts of a URL
Every URL breaks into small pieces. Each piece has a name.
https://user:pass@shop.com:8080/products/shoes?color=red&size=9#reviews | | | | | | | protocol auth hostname port pathname search hash
- protocol tells the browser how to talk, such as https.
- hostname names the website.
- port picks the door on the server.
- pathname points to the page.
- search carries extra details after the question mark.
- hash jumps to a spot inside the page.
The URL Class
The URL class is a global tool. You need no import. Pass a full address to create a URL object.
const address = new URL("https://shop.com:8080/products/shoes?color=red&size=9#reviews");
console.log(address.protocol); // https:
console.log(address.hostname); // shop.com
console.log(address.port); // 8080
console.log(address.pathname); // /products/shoes
console.log(address.search); // ?color=red&size=9
console.log(address.hash); // #reviews
console.log(address.origin); // https://shop.com:8080Change a URL
Every property accepts a new value. Node.js rebuilds the full address for you.
address.pathname = "/products/boots";
address.port = "443";
console.log(address.href);Relative Addresses
Pass a base address as the second value to complete a short path.
const page = new URL("/cart", "https://shop.com");
console.log(page.href); // https://shop.com/cartRead Search Words with URLSearchParams
The searchParams property holds the words after the question mark. It works like a small notebook of name and value pairs.
const params = address.searchParams;
console.log(params.get("color")); // red
console.log(params.has("size")); // true
params.append("brand", "Zoom");
params.set("size", "10");
params.delete("color");
console.log(address.search); // ?size=10&brand=ZoomLoop Over All Pairs
for (const [name, value] of params) {
console.log(name + " = " + value);
}Build Search Words from an Object
const query = new URLSearchParams({ q: "node js", page: 2 });
console.log(query.toString()); // q=node+js&page=2The class replaces spaces and special symbols with safe codes. This step prevents broken links.
Handle Bad Input
A wrong address throws an error. Wrap the code in a try and catch block when the address comes from a user.
try {
const bad = new URL("not a url");
} catch (error) {
console.log("Invalid address");
}Newer Node.js versions also offer URL.canParse, which returns true or false without an error.
Read Addresses in a Web Server
A server receives only the path and search words in req.url. Add the host name to build a full URL object.
const http = require("http");
http.createServer((req, res) => {
const full = new URL(req.url, "http://" + req.headers.host);
const name = full.searchParams.get("name") || "friend";
res.end("Hello, " + name);
}).listen(3000);Visit http://localhost:3000/?name=Asha to see Hello, Asha.
Browser asks: /?name=Asha
|
v
new URL(...) --> searchParams.get("name")
|
v
Server replies: Hello, Asha
File Paths and File URLs
The URL module converts between file URLs and normal paths. ES modules use this skill often.
const { fileURLToPath, pathToFileURL } = require("url");
console.log(fileURLToPath("file:///home/user/app/index.js"));
console.log(pathToFileURL("/home/user/app/index.js").href);Old Methods to Avoid
Older tutorials show url.parse and url.format. Node.js marks these methods as legacy. Use the URL class for all new code.
Practice Tasks
- Parse a product link and print its hostname and pathname.
- Read a page number from the search words and add one to it.
- Build a search link from an object with two keys.
