📜  Node.js URL.port API(1)

📅  最后修改于: 2023-12-03 15:17:55.916000             🧑  作者: Mango

Node.js URL.port API

在 Node.js 中,URL.port API 可以用来获取或设置 URL 字符串中的端口号部分。此外,URL 对象还提供了其他有用的方法和属性,例如解析 URL 字符串中的各个组成部分和构建新的 URL 字符串。

获取 URL 字符串中的端口号

要获取 URL 字符串中的端口号,可以使用 url.parse() 方法将 URL 字符串解析为 URL 对象,然后访问 port 属性。示例代码如下:

const url = require('url');
const myUrl = url.parse('https://www.example.com:8080/path/to/myfile.html');
console.log(myUrl.port);
// 输出 8080
设置 URL 对象的端口号

要设置 URL 对象的端口号,可以直接赋值给 port 属性。示例代码如下:

const url = require('url');
const myUrl = new URL('https://www.example.com/path/to/myfile.html');
myUrl.port = 8080;
console.log(myUrl.href);
// 输出 https://www.example.com:8080/path/to/myfile.html
判断 URL 是否指定了端口号

可以通过 url.port 属性是否为 null 或字符串类型的数字来判断 URL 是否指定了端口号。示例代码如下:

const url = require('url');
const myUrl1 = new URL('https://www.example.com/path/to/myfile.html');
const myUrl2 = new URL('https://www.example.com:8080/path/to/myfile.html');
console.log(myUrl1.port); // 输出 null
console.log(myUrl2.port); // 输出 8080
console.log(myUrl1.port === null); // 输出 true
console.log(typeof myUrl2.port === 'string'); // 输出 true
参考链接