Node.js中URL模块详解

Node.js 中 URL 模块全部 API 详解

1. URL 类

const { URL } = require('url');// 1. 创建 URL 对象
const url = new URL('https://www.example.com:8080/path?query=value#hash');// 2. URL 属性
console.log('协议:', url.protocol);      // 'https:'
console.log('主机名:', url.hostname);    // 'www.example.com'
console.log('端口:', url.port);          // '8080'
console.log('主机:', url.host);          // 'www.example.com:8080'
console.log('路径:', url.pathname);      // '/path'
console.log('查询字符串:', url.search);   // '?query=value'
console.log('查询参数:', url.searchParams); // URLSearchParams 对象
console.log('哈希:', url.hash);          // '#hash'
console.log('完整 URL:', url.href);      // 'https://www.example.com:8080/path?query=value#hash'
console.log('源:', url.origin);          // 'https://www.example.com'
console.log('用户名:', url.username);    // ''
console.log('密码:', url.password);      // ''// 3. 修改 URL 属性
url.protocol = 'http:';
url.hostname = 'example.com';
url.port = '80';
url.pathname = '/new-path';
url.search = '?new=query';
url.hash = '#new-hash';
url.username = 'user';
url.password = 'pass';// 4. URL 字符串化
console.log('URL 字符串:', url.toString());
console.log('URL JSON:', url.toJSON());

2. URLSearchParams 类

const { URLSearchParams } = require('url');// 1. 创建 URLSearchParams 对象
const params = new URLSearchParams('key1=value1&key2=value2');// 2. 添加参数
params.append('key3', 'value3');
params.append('key3', 'value4'); // 可以添加同名参数// 3. 获取参数
console.log('获取参数:', params.get('key1'));     // 'value1'
console.log('获取所有参数:', params.getAll('key3')); // ['value3', 'value4']// 4. 检查参数是否存在
console.log('参数是否存在:', params.has('key1')); // true// 5. 删除参数
params.delete('key2');// 6. 设置参数
params.set('key1', 'new-value'); // 替换已存在的参数// 7. 遍历参数
for (const [key, value] of params) {console.log(`${key}: ${value}`);
}// 8. 转换为字符串
console.log('参数字符串:', params.toString());// 9. 排序参数
params.sort();// 10. 清空参数
params.forEach((value, key) => {params.delete(key);
});

3. URL 解析和格式化

const { URL, URLSearchParams } = require('url');// 1. 解析 URL
function parseURL(urlString) {try {const url = new URL(urlString);return {protocol: url.protocol,hostname: url.hostname,port: url.port,pathname: url.pathname,search: url.search,hash: url.hash,username: url.username,password: url.password,origin: url.origin};} catch (error) {console.error('URL 解析错误:', error);return null;}
}// 2. 构建 URL
function buildURL(options) {const url = new URL('https://example.com');if (options.protocol) url.protocol = options.protocol;if (options.hostname) url.hostname = options.hostname;if (options.port) url.port = options.port;if (options.pathname) url.pathname = options.pathname;if (options.search) url.search = options.search;if (options.hash) url.hash = options.hash;if (options.username) url.username = options.username;if (options.password) url.password = options.password;return url.toString();
}// 3. 解析查询字符串
function parseQueryString(queryString) {const params = new URLSearchParams(queryString);const result = {};for (const [key, value] of params) {result[key] = value;}return result;
}// 4. 构建查询字符串
function buildQueryString(params) {const searchParams = new URLSearchParams();for (const [key, value] of Object.entries(params)) {searchParams.append(key, value);}return searchParams.toString();
}

4. URL 验证和规范化

const { URL } = require('url');// 1. 验证 URL
function isValidURL(urlString) {try {new URL(urlString);return true;} catch (error) {return false;}
}// 2. 规范化 URL
function normalizeURL(urlString) {try {const url = new URL(urlString);// 移除默认端口if (url.port === '80' && url.protocol === 'http:') {url.port = '';}if (url.port === '443' && url.protocol === 'https:') {url.port = '';}// 规范化路径url.pathname = url.pathname.replace(/\/+/g, '/');if (url.pathname !== '/' && url.pathname.endsWith('/')) {url.pathname = url.pathname.slice(0, -1);}return url.toString();} catch (error) {return urlString;}
}// 3. 解析相对 URL
function resolveURL(base, relative) {try {return new URL(relative, base).toString();} catch (error) {return null;}
}// 4. 提取 URL 组件
function extractURLComponents(urlString) {try {const url = new URL(urlString);return {protocol: url.protocol.replace(':', ''),domain: url.hostname,port: url.port || (url.protocol === 'https:' ? '443' : '80'),path: url.pathname,query: url.search.slice(1),hash: url.hash.slice(1)};} catch (error) {return null;}
}

5. URL 编码和解码

const { URL, URLSearchParams } = require('url');// 1. URL 编码
function encodeURL(urlString) {try {const url = new URL(urlString);return url.toString();} catch (error) {return encodeURI(urlString);}
}// 2. URL 解码
function decodeURL(urlString) {try {return decodeURI(urlString);} catch (error) {return urlString;}
}// 3. 参数编码
function encodeParams(params) {const searchParams = new URLSearchParams();for (const [key, value] of Object.entries(params)) {searchParams.append(key, value);}return searchParams.toString();
}// 4. 参数解码
function decodeParams(queryString) {const params = new URLSearchParams(queryString);const result = {};for (const [key, value] of params) {result[key] = value;}return result;
}

6. URL 操作工具

const { URL, URLSearchParams } = require('url');// 1. URL 合并
function mergeURLs(base, relative) {try {return new URL(relative, base).toString();} catch (error) {return null;}
}// 2. URL 比较
function compareURLs(url1, url2) {try {const u1 = new URL(url1);const u2 = new URL(url2);return {sameProtocol: u1.protocol === u2.protocol,sameHost: u1.host === u2.host,samePath: u1.pathname === u2.pathname,sameQuery: u1.search === u2.search,sameHash: u1.hash === u2.hash,isEqual: u1.href === u2.href};} catch (error) {return null;}
}// 3. URL 转换
function transformURL(urlString, options) {try {const url = new URL(urlString);if (options.protocol) url.protocol = options.protocol;if (options.hostname) url.hostname = options.hostname;if (options.port) url.port = options.port;if (options.pathname) url.pathname = options.pathname;if (options.search) url.search = options.search;if (options.hash) url.hash = options.hash;return url.toString();} catch (error) {return null;}
}// 4. URL 验证器
class URLValidator {constructor(options = {}) {this.options = {protocols: ['http:', 'https:'],requireProtocol: true,...options};}validate(urlString) {try {const url = new URL(urlString);if (this.options.requireProtocol && !url.protocol) {return false;}if (this.options.protocols && !this.options.protocols.includes(url.protocol)) {return false;}return true;} catch (error) {return false;}}
}

7. 实际应用示例

const { URL, URLSearchParams } = require('url');// 1. URL 路由解析器
class URLRouter {constructor() {this.routes = new Map();}addRoute(pattern, handler) {this.routes.set(pattern, handler);}match(urlString) {const url = new URL(urlString);const pathname = url.pathname;for (const [pattern, handler] of this.routes) {const regex = new RegExp(pattern);if (regex.test(pathname)) {return {handler,params: this.extractParams(pattern, pathname),query: Object.fromEntries(url.searchParams)};}}return null;}extractParams(pattern, pathname) {const params = {};const patternParts = pattern.split('/');const pathParts = pathname.split('/');for (let i = 0; i < patternParts.length; i++) {if (patternParts[i].startsWith(':')) {const paramName = patternParts[i].slice(1);params[paramName] = pathParts[i];}}return params;}
}// 2. URL 参数处理器
class URLParamHandler {constructor() {this.params = new URLSearchParams();}setParams(params) {for (const [key, value] of Object.entries(params)) {this.params.set(key, value);}}getParams() {return Object.fromEntries(this.params);}removeParam(key) {this.params.delete(key);}clearParams() {this.params = new URLSearchParams();}toString() {return this.params.toString();}
}// 3. URL 重写器
class URLRewriter {constructor(rules) {this.rules = rules;}rewrite(urlString) {const url = new URL(urlString);for (const rule of this.rules) {if (rule.pattern.test(url.pathname)) {url.pathname = url.pathname.replace(rule.pattern, rule.replacement);}}return url.toString();}
}// 4. URL 监控器
class URLMonitor {constructor() {this.history = new Map();}track(urlString) {const url = new URL(urlString);const key = url.origin + url.pathname;if (!this.history.has(key)) {this.history.set(key, {count: 0,lastAccess: null,params: new Map()});}const entry = this.history.get(key);entry.count++;entry.lastAccess = new Date();for (const [key, value] of url.searchParams) {if (!entry.params.has(key)) {entry.params.set(key, new Set());}entry.params.get(key).add(value);}}getStats() {const stats = [];for (const [url, data] of this.history) {stats.push({url,count: data.count,lastAccess: data.lastAccess,params: Object.fromEntries(Array.from(data.params.entries()).map(([key, values]) => [key,Array.from(values)]))});}return stats;}
}

URL 模块的主要特点:

  1. 提供 URL 解析和构建功能
  2. 支持查询参数处理
  3. 提供 URL 编码和解码
  4. 支持 URL 验证和规范化
  5. 提供 URL 组件提取和操作

使用建议:

  1. 使用 URL 类处理 URL 字符串
  2. 使用 URLSearchParams 处理查询参数
  3. 注意 URL 编码和解码
  4. 验证 URL 格式
  5. 规范化 URL 路径和参数

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/75709.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java接口性能优化面试问题集锦:高频考点与深度解析

1. 如何定位接口性能瓶颈&#xff1f;常用哪些工具&#xff1f; 考察点&#xff1a;性能分析工具的使用与问题定位能力。 核心答案&#xff1a; 工具&#xff1a;Arthas&#xff08;在线诊断&#xff09;、JProfiler&#xff08;内存与CPU分析&#xff09;、VisualVM、Prometh…

WheatA小麦芽:农业气象大数据下载器

今天为大家介绍的软件是WheatA小麦芽&#xff1a;专业纯净的农业气象大数据系统。下面&#xff0c;我们将从软件的主要功能、支持的系统、软件官网等方面对其进行简单的介绍。 主要内容来源于软件官网&#xff1a;WheatA小麦芽的官方网站是http://www.wheata.cn/ &#xff0c;…

Python10天突击--Day 2: 实现观察者模式

以下是 Python 实现观察者模式的完整方案&#xff0c;包含同步/异步支持、类型注解、线程安全等特性&#xff1a; 1. 经典观察者模式实现 from abc import ABC, abstractmethod from typing import List, Anyclass Observer(ABC):"""观察者抽象基类""…

CST1019.基于Spring Boot+Vue智能洗车管理系统

计算机/JAVA毕业设计 【CST1019.基于Spring BootVue智能洗车管理系统】 【项目介绍】 智能洗车管理系统&#xff0c;基于 Spring Boot Vue 实现&#xff0c;功能丰富、界面精美 【业务模块】 系统共有三类用户&#xff0c;分别是&#xff1a;管理员用户、普通用户、工人用户&…

Windows上使用Qt搭建ARM开发环境

在 Windows 上使用 Qt 和 g++-arm-linux-gnueabihf 进行 ARM Linux 交叉编译(例如针对树莓派或嵌入式设备),需要配置 交叉编译工具链 和 Qt for ARM Linux。以下是详细步骤: 1. 安装工具链 方法 1:使用 MSYS2(推荐) MSYS2 提供 mingw-w64 的 ARM Linux 交叉编译工具链…

Python爬虫教程011:scrapy爬取当当网数据开启多条管道下载及下载多页数据

文章目录 3.6.4 开启多条管道下载3.6.5 下载多页数据3.6.6 完整项目下载3.6.4 开启多条管道下载 在pipelines.py中新建管道类(用来下载图书封面图片): # 多条管道开启 # 要在settings.py中开启管道 class DangdangDownloadPipeline:def process_item(self, item, spider):…

Mysql -- 基础

SQL SQL通用语法&#xff1a; SQL分类&#xff1a; DDL: 数据库操作 查询&#xff1a; SHOW DATABASES&#xff1b; 创建&#xff1a; CREATE DATABASE[IF NOT EXISTS] 数据库名 [DEFAULT CHARSET字符集] [COLLATE 排序规则]&#xff1b; 删除&#xff1a; DROP DATABA…

实操(环境变量)Linux

环境变量概念 我们用语言写的文件编好后变成了程序&#xff0c;./ 运行的时候他就会变成一个进程被操作系统调度并运行&#xff0c;运行完毕进程相关资源被释放&#xff0c;因为它是一个bash的子进程&#xff0c;所以它退出之后进入僵尸状态&#xff0c;bash回收他的退出结果&…

torch.cat和torch.stack的区别

torch.cat 和 torch.stack 是 PyTorch 中用于组合张量的两个常用函数&#xff0c;它们的核心区别在于输入张量的维度和输出张量的维度变化。以下是详细对比&#xff1a; 1. torch.cat (Concatenate) 作用&#xff1a;沿现有维度拼接多个张量&#xff0c;不创建新维度 输入要求…

深入解析@Validated注解:Spring 验证机制的核心工具

一、注解出处与核心定位 1. 注解来源 • 所属框架&#xff1a;Validated 是 Spring Framework 提供的注解&#xff08;org.springframework.validation.annotation 包下&#xff09;。 • 核心定位&#xff1a; 作为 Spring 对 JSR-380&#xff08;Bean Validation 2.0&#…

2025年认证杯数学建模竞赛A题完整分析论文(含模型、可运行代码)(共32页)

2025年认证杯数学建模竞赛A题完整分析论文 目录 摘要 一、问题分析 二、问题重述 三、模型假设 四、 模型建立与求解 4.1问题1 4.1.1问题1解析 4.1.2问题1模型建立 4.1.3问题1样例代码&#xff08;仅供参考&#xff09; 4.1.4问题1求解结果分析&#xff08…

Google A2A协议,是为了战略性占领标准?

一、导读 2025 年 4 月 9 日&#xff0c;Google 正式发布了 Agent2Agent&#xff08;A2A&#xff09;协议。 A2A 协议致力于打破智能体之间的隔阂&#xff0c;让它们能够跨越框架和供应商的限制&#xff0c;以一种标准化、开放的方式进行沟通与协作 截止到现在&#xff0c;代…

Ansible:roles角色

文章目录 Roles角色Ansible Roles目录编排Roles各目录作用创建 roleplaybook调用角色调用角色方法1&#xff1a;调用角色方法2&#xff1a;调用角色方法3&#xff1a; roles 中 tags 使用实战案例 Roles角色 角色是ansible自1.2版本引入的新特性&#xff0c;用于层次性、结构化…

MCU的USB接口作为 USB CDC串口输出

引用&#xff1a; https://microchip-mplab-harmony.github.io/usb_apps_device/apps/usb_uart_bridge_dual/readme.html STM32 USB使用记录&#xff1a;使用CDC类虚拟串口&#xff08;VCP&#xff09;进行通讯_stm32 usb使用记录:使用cdc类虚拟串口(vcp)进行通讯-CSDN博客 前…

深度解析强化学习:原理、算法与实战

深度解析强化学习:原理、算法与实战 0. 前言1. 强化学习基础1.1 基本概念1.2 马尔科夫决策过程1.3 目标函数1.4 智能体学习过程2. 计算状态值3. 计算状态-动作值4. Q 学习4.1 Q 值4.2 使用 Q 学习进行 frozen lake 游戏4.3. frozen lake 问题4.4 实现 Q 学习小结系列链接0. 前…

UE5蓝图之间的通信------接口

一、创建蓝图接口 二、双击创建的蓝图接口&#xff0c;添加函数&#xff0c;并重命名新函数。 三、在一个蓝图&#xff08;如玩家角色蓝图&#xff09;中实现接口&#xff0c;如下图&#xff1a; 步骤一&#xff1a;点击类设置 步骤二&#xff1a;在细节面板已经实现的接口中…

2025 年“认证杯”数学中国数学建模网络挑战赛 A题 小行星轨迹预测

近地小行星&#xff08; Near Earth Asteroids, NEAs &#xff09;是轨道相对接近地球的小行 星&#xff0c;它的正式定义为椭圆轨道的近日距不大于 1.3 天文单位&#xff08; AU &#xff09;的小行星。 其中轨道与地球轨道最近距离小于 0.05A 且直径大于 140 米的小行星被…

Axure中继器(Repeater): 列表多选和 列表查询

文章目录 引言I 列表多选添加选中交互事件添加未选中交互事件II 列表查询知识点操作说明引言 基于鼠标点击交互事件实现列表多选列表查询 I 列表多选 添加选中交互事件 给列标题第一列多选框元件命名为ckeck,并同时添加选中交互事件; 同步添加设置选择/选中动作,目标元件选…

windows11下pytorch(cpu)安装

先装anaconda 见最下方 Pytorch 官网&#xff1a;PyTorch 找到下图&#xff08;不要求版本一样&#xff09;&#xff08;我的电脑是集显&#xff08;有navdia的装gpu&#xff09;&#xff0c;装cpu&#xff09; 查看已有环境列表 创建环境 conda create –n 虚拟环境名字(…

最新版IDEA超详细图文安装教程(适用Mac系统)附安装包及补丁2025最新教程

目录 前言 一、IDEA最新版下载 二、IDEA安装 三、IDEA补丁 前言 IDEA&#xff08;IntelliJ IDEA&#xff09;是专为Java语言设计的集成开发环境&#xff08;IDE&#xff09;&#xff0c;由JetBrains公司开发&#xff0c;被公认为业界最优秀的Java开发工具之一。DEA全称Int…