Beginner Node.js Interview QuestionsBeginnerConcept
Node.js · Question 29
What is the Node.js url module?
Direct answer
The url module parses and formats URLs — use new URL() (WHATWG API, global in Node) or url.parse legacy; extract pathname, searchParams, and hostname for routing and query handling.
req.url on a server is often path + query only (/interviews?page=2), not a full URL — construct a base URL or parse with URL class carefully.
- new URL(input, base) — recommended WHATWG API; searchParams is URLSearchParams.
- pathname — route matching without query string.
- fileURLToPath — converts file:// URLs from import.meta.url to OS paths (Q22).
url-parse.mjs
const absolute = new URL("https://acedevhub.com/interviews/nodejs?page=2&sort=asc");
console.log(absolute.pathname); // /interviews/nodejs
console.log(absolute.hostname); // acedevhub.com
console.log(absolute.searchParams.get("page")); // "2"
// Server-relative req.url
const reqUrl = "/interviews/nodejs-interview-questions?limit=10";
const parsed = new URL(reqUrl, "http://localhost");
console.log(parsed.pathname);