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'
相关推荐
念九_ysl6 分钟前
前端循环全解析:JS/ES/TS 循环写法与实战示例
前端·javascript·typescript
前端御书房3 小时前
前端PDF转图片技术调研实战指南:从踩坑到高可用方案的深度解析
前端·javascript
程序员黄同学4 小时前
请谈谈 Vue 中的响应式原理,如何实现?
前端·javascript·vue.js
宁波阿成5 小时前
vue3里组件的v-model:value与v-model的区别
前端·javascript·vue.js
柯腾啊5 小时前
VSCode 中使用 Snippets 设置常用代码块
开发语言·前端·javascript·ide·vscode·编辑器·代码片段
Jay丶萧邦5 小时前
el-select:有关多选,options选项值不包含绑定值的回显问题
javascript·vue.js·elementui
pixle06 小时前
Three.js 快速入门教程【一】开启你的 3D Web 开发之旅
前端·javascript·3d
我爱学习_zwj6 小时前
后台管理系统-月卡管理
javascript·vue.js·elementui
录大大i6 小时前
HtML之JavaScript BOM编程
前端·javascript·html
乐多_L8 小时前
使用vue3框架vue-next-admin导出表格excel(带图片)
前端·javascript·vue.js