内置模块 URL
约 328 字大约 1 分钟
2025-03-15
一、模块概述
URL 模块的主要作用是 解析 和 处理 URL,可以实现 URL字符串
和 URL对象的互相转化
,提供了一系列的方法,来操作或者读取 URL 对象。
二、url.parse()解析
这是 url 模块中最常用的方法之一。它接受一个 URL 字符串作为输入,并返回一个包含 URL 各个部分的对象。 例如:
const url = require("url");
const myURL = "https://example.com:8080/path/to/file?name=value#fragment";
const parsedURL = url.parse(myURL);
console.log(parsedURL);
输出结果:
{
"protocol": "https:",
"slashes": true,
"host": "example.com:8080",
"port": "8080",
"hostname": "example.com",
"hash": "#fragment",
"search": "?name=value",
"query": "name=value",
"pathname": "/path/to/file",
"path": "/path/to/file?name=value",
"href": "https://example.com:8080/path/to/file?name=value#fragment"
}
特殊说明
url.parse()
可以接受第二个参数,格式为布尔值,设置为 true 的时候,那么 query 属性的值将是一个经过 querystring.parse()方法处理后的对象,而不是一个字符串。
例如:
const parsedURL = url.parse(myURL, true);
console.log(parsedURL.query);
输出结果:
{
"name": "value",
"age": 20
}
三、url.format() 格式化
url.format()
与与url.parse()
相反,它接受一个包含 URL 各个部分的对象,并返回一个格式化后的 URL 字符串。例如:
const url = require("url");
const urlObject = {
protocol: "https:",
hostname: "example.com",
port: "8080",
pathname: "/path/to/file",
search: "?name=value",
hash: "#fragment",
};
const newURL = url.format(urlObject);
console.log(newURL);
输出结果:https://example.com:8080/path/to/file?name=value#fragment
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于