Node.js URL Module
In Node.js, the URL module is used to parse and manipulate URLs. It is a core module that is included with the Node.js installation. In this tutorial, we'll discuss how to use the URL module in Node.js.
Syntax
The basic syntax for using the URL module in Node.js is:
const url = require('url');
This will include the built-in URL module in your Node.js application.
Example
Here's an example of how to use the URL module in Node.js:
const url = require('url');
const myUrl = new URL('http://example.com:8000/hello.html?id=100&status=active');
// Serialized URL
console.log(myUrl.href); // Output: 'http://example.com:8000/hello.html?id=100&status=active'
// Host (root domain)
console.log(myUrl.host); // Output: 'example.com:8000'
// Hostname (does not include port number)
console.log(myUrl.hostname); // Output: 'example.com'
// Pathname
console.log(myUrl.pathname); // Output: '/hello.html'
// Query string
console.log(myUrl.search); // Output: '?id=100&status=active'
// Search parameters
console.log(myUrl.searchParams); // Output: URLSearchParams { 'id' => '100', 'status' => 'active' }
// Get specific search parameter value
console.log(myUrl.searchParams.get('id')); // Output: '100'
Output
When we run the example code above, the output will be:
http://example.com:8000/hello.html?id=100&status=active
example.com:8000
example.com
/hello.html
?id=100&status=active
URLSearchParams { 'id' => '100', 'status' => 'active' }
100
This output shows how to use various methods in the URL module to extract specific parts of a URL.
Explanation
In the example above, we included the URL module using the require() function. We then created a new URL object using the URL constructor and passed in a URL string. We used various methods of the URL object to extract specific parts of the URL.
Use
The URL module is useful for parsing and manipulating URLs. You can use it to extract parts of a URL such as the hostname, pathname, query string, and search parameters. You can also modify or build URLs using the methods provided by the URL module.
Important Points
- The URL module is included with Node.js and does not require any additional installation.
- The URL module can be used to parse and manipulate URLs in both server-side and client-side JavaScript code.
- The properties and methods of the URL object allow you to easily extract and modify parts of URLs.
Summary
In this tutorial, we discussed how to use the URL module in Node.js to parse and manipulate URLs. We covered the syntax, example, output, explanation, use, and important points of the URL module. With this knowledge, you can now use the URL module in your Node.js applications to easily extract and manipulate URLs.