Performance: URL class for parsing
This affects how quickly and efficiently URLs are parsed and manipulated in Node.js applications, impacting server response time and memory usage.
Jump into concepts and practice - no test required
const { URL } = require('url');
const myURL = new URL(request.url, `http://${request.headers.host}`);
const hostname = myURL.hostname;
const pathname = myURL.pathname;const url = require('url');
const parsedUrl = url.parse(request.url);
const hostname = parsedUrl.host;
const pathname = parsedUrl.pathname;| Pattern | CPU Usage | Memory Usage | Parsing Speed | Verdict |
|---|---|---|---|---|
| Legacy url.parse() | Higher due to string parsing | Higher due to plain object creation | Slower due to manual parsing | [X] Bad |
| URL class | Lower with optimized parsing | Lower with structured objects | Faster with built-in methods | [OK] Good |
URL class in Node.js primarily help you do?https://example.com/path?name=abc in Node.js?new keyword and a string argument: new URL(string).new. const url = url.parse('https://example.com/path?name=abc'); uses old url.parse method, not the URL class. const url = new URL.parse('https://example.com/path?name=abc'); incorrectly combines new and URL.parse.new URL() to create URL objects [OK]const url = new URL('https://example.com:8080/path/page?query=123#section');
console.log(url.hostname);
console.log(url.port);
console.log(url.pathname);
console.log(url.hash);hostname gives domain without port, port gives port number, pathname gives path starting with '/', hash includes '#' plus fragment.const url = new URL('https://example.com/path');
url.hostname = 'newsite.com';
url.port = 3000;
url.pathname = 'newpath';
console.log(url.href);url.pathname = 'newpath' normalizes the path by adding a leading slash, resulting in '/newpath'.id to 42 in this URL: https://shop.com/products?category=books&id=10. Which code correctly updates the URL using the URL class?searchParams with methods like set() to update query parameters safely.searchParams.set(), which is correct. Options A, C, and D use invalid properties or methods not available on URL objects.