Node常用内置模块之url模块和querystring模块

1、URL类

url模块在v16的nodejs中已经明确被废弃,在将来的升级node中,可能被不支持。

官网建议在废弃url、querystring模块后,采用URL类去替代

图示 URL 各部分

旧版的url模块

作用url 模块是用于处理和解析 URL 的模块,能够将 URL 字符串解析为 URL 对象并反向操作,即将 URL 对象转换为 URL 字符串。

js 复制代码
const url = require('url');

常用的方法

  1. parse(urlString[, parseQueryString[, slashesDenoteHost]]):将一个 URL 字符串解析成一个 URL 对象。
  2. format(urlObject):将一个 URL 对象格式化成一个 URL 字符串。
  3. resolve(from, to):解析一个相对路径,返回完整的 URL 字符串。
js 复制代码
const url = require('url');

// 解析 URL 字符串
const urlString = 'https://www.example.com/path?query=string#hash';
const urlObj = url.parse(urlString);
console.log(urlObj);
// Url {
//  protocol: 'https:',
//  slashes: true,
//  auth: null,
//  host: 'www.example.com',
//  port: null,
//  hostname: 'www.example.com',
//  hash: '#hash',
//  search: '?query=string',
//  query: 'query=string',
//  pathname: '/path',
//  path: '/path?query=string',
//  href: 'https://www.example.com/path?query=string#hash'
// }

// 将 URL 对象转换为字符串
const urlObject = {
  protocol: 'https:',
  slashes: true,
  hostname: 'www.example.com',
  pathname: '/path',
  search: '?query=string',
  hash: '#hash'
};
const newUrl = url.format(urlObject);
console.log(newUrl);
// https://www.example.com/path?query=string#hash

// 解析相对路径
const from = 'https://www.example.com/path';
const to = '../file.txt';
const resolvedUrl = url.resolve(from, to);
console.log(resolvedUrl);
// https://www.example.com/file.txt
参数 描述 示例
href 解析前的完整原始 URL,协议名和主机名已转为小写 http://user:pass@host.com:8080/p/a/t/h?query=string#hash
protocol 请求协议,小写 http:
slashes 协议的":"号后是否有"/" true or false
host URL主机名,包括端口信息,小写 'host.com:8080'
auth URL中的认证信息 'user:pass'
hostname 主机名,小写 'host.com'
port 主机的端口号 '8080'
pathname URL中路径 '/p/a/t/h'
search 查询对象,即:queryString,包括之前的问号"?" '?query=string'
path pathname 和 search的合集 '/p/a/t/h?query=string'
query 查询字符串中的参数部分(问号后面部分字符串) 'query=string' or {'query':'string'}
hash 锚点部分(即:"#"及其后的部分) '#hash'
相关推荐
视图猿人2 小时前
RxJS基本使用及在next.js中使用的例子
开发语言·javascript
bitbitDown3 小时前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
冴羽4 小时前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘4 小时前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉4 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
不爱吃糖的程序媛5 小时前
Electron 应用中的系统检测方案对比
前端·javascript·electron
pe7er5 小时前
用高阶函数实现递归:从匿名函数到通用递归生成器
前端·javascript
Jonathan Star6 小时前
NestJS 是基于 Node.js 的渐进式后端框架,核心特点包括 **依赖注入、模块化架构、装饰器驱动、TypeScript 优先、与主流工具集成** 等
开发语言·javascript·node.js
矢心6 小时前
setTimeout 和 setInterval:看似简单,但你不知道的使用误区
前端·javascript·面试
一枚前端小能手6 小时前
🧭 使用历史记录 API - SPA导航与状态管理的完整指南
前端·javascript