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'
相关推荐
ホロHoro15 分钟前
学习笔记:JavaScript(4)——DOM节点
javascript·笔记·学习
一只小风华~1 小时前
Vue: ref、reactive、shallowRef、shallowReactive
前端·javascript·vue.js
云枫晖2 小时前
JS核心知识-this的指向
前端·javascript
前端人类学2 小时前
现代贪吃蛇游戏的进化:从经典玩法到多人在线体验
javascript·css
前端康师傅2 小时前
JavaScript 函数高级用法
前端·javascript
前端Hardy2 小时前
惊艳同事的 Canvas 事件流程图,这篇教会你
前端·javascript·css
华仔啊3 小时前
别再被 Stream.toMap() 劝退了!3 个真实避坑案例,建议收藏
javascript·后端
华仔啊3 小时前
别再写 TypeScript enum了!新枚举方式让 bundle 瞬间小20%
javascript·typescript
方安乐3 小时前
vite+vue+js项目使用ts报错
前端·javascript·vue.js
njsgcs3 小时前
网页连接摄像头
javascript·css·html