![]() |
| Gambar noje.js URL Module |
The Node.js URL module provides a way of working with URLs in a manner that is similar to the web browser API. It allows you to parse URLs, create new ones, and manipulate the parts of a URL such as the protocol, host, port, path, and query string.
Here is an example of using the URL module to parse a URL:
const url = require('url');
const myUrl = new URL('https://example.com:3000/hello.html?id=100&status=active');
console.log(myUrl.protocol); // https:
console.log(myUrl.host); // example.com:3000
console.log(myUrl.hostname); // example.com
console.log(myUrl.port); // 3000
console.log(myUrl.pathname); // /hello.html
console.log(myUrl.search); // ?id=100&status=active
console.log(myUrl.searchParams); // URLSearchParams { 'id' => '100', 'status' => 'active' }
console.log(myUrl.hash); // (empty string)
You can also use the `URL` constructor to create a new URL from a base URL and a relative URL:
const baseUrl = new URL('https://example.com/base/path/');
const relativeUrl = new URL('../other/path', baseUrl);
console.log(relativeUrl.href); // https://example.com/base/other/path
The URL module also provides the `parse` function, which allows you to parse a URL string into an object with properties for each part of the URL:
const url = require('url');
const myUrl = url.parse('https://example.com:3000/hello.html?id=100&status=active');
console.log(myUrl.protocol); // https:
console.log(myUrl.host); // example.com:3000
console.log(myUrl.pathname); // /hello.html
console.log(myUrl.query); // id=100&status=active
You can also use the `format` function to create a URL string from an object containing the parts of the URL:
const url = require('url');
const myUrl = {
protocol: 'https:',
host: 'example.com:3000',
pathname: '/hello.html',
query: {
id: 100,
status: 'active'
}
};
console.log(url.format(myUrl)); // https://example.com:3000/hello.html?id=100&status=active

Posting Komentar