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.pswp.cn/web/75709.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/75709.shtml
英文地址,請注明出處:http://en.pswp.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…