How to use the port function from url

Find comprehensive JavaScript url.port code examples handpicked from public code repositorys.

url.port is a property in the Node.js url module that allows you to get or set the port portion of a URL.

5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
  break;

case 'hostname':
  url[part] = value;

  if (url.port) value += ':'+ url.port;
  url.host = value;
  break;

case 'host':
fork icon0
star icon0
watch icon1

How does url.port work?

url.port is a built-in Node.js module that provides a way to parse a URL string and extract the port number as a string, or set the port number for a given URL object. If the URL does not contain a port, the method returns an empty string.

Ai Example

1
2
3
4
5
6
const url = require("url");

const parsedUrl = url.parse(
  "https://example.com:8080/path/to/resource?param=value"
);
console.log(parsedUrl.port); // logs "8080"

In this example, the url.parse() method is used to parse the URL string into a Url object, which has a port property that holds the port number extracted from the URL. The value of parsedUrl.port in this case would be the string "8080".