📅  最后修改于: 2023-12-03 14:44:40.683000             🧑  作者: Mango
The URL.host
property in Node.js represents the hostname and port number of a URL. In this article, we will discuss how to use the URL.host
property in Node.js.
The syntax for using the URL.host
property in Node.js is as follows:
urlObject.host
Here, urlObject
is the URL object returned by the URL()
constructor.
Let's suppose we have a URL https://www.example.com:8080/path/to/my/resource.html
. To get the hostname and port number from this URL, we can use the URL.host
property as follows:
const { URL } = require('url');
const myUrl = new URL('https://www.example.com:8080/path/to/my/resource.html');
const host = myUrl.host;
console.log(host); // output: www.example.com:8080
Here, we first import the URL
module from the url
package. We then create a new URL
object from the given URL. Finally, we retrieve the host
property of this object and log it to the console.
In this article, we have discussed the basics of using the URL.host
property in Node.js. By using this property, we can easily retrieve the hostname and port number of a given URL.