📜  节点 | urlObject.port API(1)

📅  最后修改于: 2023-12-03 14:57:09.839000             🧑  作者: Mango

Node.js | urlObject.port API

Node.js provides a built-in module called url that allows you to parse URL strings and access their individual components. One of the properties of the url object is port, which represents the port number specified in the URL.

Table of Contents
Introduction to urlObject.port

The port property of the url object represents the port number mentioned in the URL. It is a numeric value indicating the network port associated with the URL.

The port property is optional and may not be present in all URLs. If the URL string contains a port number, it can be accessed using the port property of the url object.

Getting the port number from a URL

To access the port property of the url object in Node.js, you need to make use of the url module and its parse method. The parse method takes a URL string as input and returns an object representing the parsed URL.

Here's how you can extract the port number from a URL:

const url = require('url');

const urlString = 'https://example.com:8080/somepath';

const urlObject = url.parse(urlString);
const portNumber = urlObject.port;

console.log(portNumber); // Output: 8080

In the above example, we first import the url module and then define a URL string. We use the url.parse method to parse the URL string and obtain an object representation.

Next, we access the port property of the url object and assign it to the portNumber variable. Finally, we print the portNumber variable which gives us the port number mentioned in the URL.

Examples

Here are a few more examples to demonstrate the usage of the urlObject.port API:

Example 1: URL without a port number
const url = require('url');

const urlString = 'https://example.com';

const urlObject = url.parse(urlString);
const portNumber = urlObject.port;

console.log(portNumber); // Output: null

In this example, the URL string does not contain a port number. Hence, the urlObject.port will return null.

Example 2: URL with default port
const url = require('url');

const urlString = 'https://example.com:443';

const urlObject = url.parse(urlString);
const portNumber = urlObject.port;

console.log(portNumber); // Output: 443

In this example, the URL string contains the default port number for the https protocol, which is 443. The urlObject.port will return 443.

Example 3: Invalid URL
const url = require('url');

const urlString = 'not a valid url';

const urlObject = url.parse(urlString);
const portNumber = urlObject.port;

console.log(portNumber); // Output: null

In this example, the URL string is not a valid URL. The urlObject.port will return null.


The urlObject.port API in Node.js allows you to access the port number mentioned in a URL string. It can be useful when you need to work with URLs and extract specific components.