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'
相关推荐
Hilaku43 分钟前
我用 Gemini 3 Pro 手搓了一个并发邮件群发神器(附源码)
前端·javascript·github
全栈前端老曹1 小时前
【包管理】npm init 项目名后底层发生了什么的完整逻辑
前端·javascript·npm·node.js·json·包管理·底层原理
HHHHHY1 小时前
mathjs简单实现一个数学计算公式及校验组件
前端·javascript·vue.js
iReachers1 小时前
HTML打包APK(安卓APP)中下载功能常见问题和详细介绍
前端·javascript·html·html打包apk·网页打包app·下载功能
愈努力俞幸运1 小时前
vue3 demo教程(Vue Devtools)
前端·javascript·vue.js
持续前行1 小时前
在 Vue3 中使用 LogicFlow 更新节点名称
前端·javascript·vue.js
Anita_Sun1 小时前
Underscore.js 整体设计思路与架构分析
前端·javascript
Java陈序员1 小时前
告别手写礼簿!一款开源免费的电子红白喜事礼簿系统!
javascript·css·html
赵明飞1 小时前
深入解析LoRaWAN协议架构与核心组件:为什么NS服务器如此关键?
javascript
咖啡の猫1 小时前
TypeScript-Babel
前端·javascript·typescript