NodeJS URL Modules
URL Modules
Url module is one of the core modules in NodeJS, which provides utilities for URL resolution and parsing. To include the URL module, use the require() method:-
var url = require('url');
The NodeJS URL module is one of the very important modules, which provides various properties to deal with URL, which includes the following:-
| URL Module Properties | Description |
|---|---|
| href | It provides the complete URL string. |
| protocol | It is used to gets and sets the protocol portion of the URL. |
| host | It returns the hostname and port number. |
| hostname | It returns the lower-cased hostname portion of the host component. |
| port | It returns the port number specified in the URL. |
| pathname | It is used to gets and sets the path portion of the URL. |
| search | It is used to gets and sets the serialized query portion of the URL. |
| query | It returns either the params portion of the query string, or a querystring-parsed object. |
| hash | It is used to gets and sets the fragment portion of the URL. |
Key Takeaways
- The URL class (WHATWG URL API) is the modern way to parse and construct URLs in Node.js.
- new URL(urlString) parses a URL into its components: protocol, hostname, pathname, search, hash.
- URLSearchParams makes it easy to read and modify query string parameters.
- The legacy url.parse() is deprecated - use the WHATWG URL API instead.
- url.resolve() is also deprecated - use new URL(path, base) for URL resolution.
- Always encode user input in URLs using encodeURIComponent() to prevent injection attacks.
See Also
Related Node.js Topics