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'
相关推荐
言兴3 分钟前
从输入 URL 到页面显示:深入理解浏览器缓存机制
前端·javascript·面试
讨厌吃蛋黄酥3 分钟前
前端跨域难题终结者:从JSONP到CORS,一文搞定所有跨域问题!
前端·javascript·后端
阿星做前端4 分钟前
coze源码解读:项目启动
前端·javascript
言兴4 分钟前
面试题之解析“类组件”与“组件”的本质
前端·javascript·面试
aidingni88811 分钟前
告别 DDL 难题:使用 Skapi 的零设置关系数据库 API
前端·javascript
东北南西15 分钟前
设计模式-单例模式
前端·javascript·单例模式·设计模式
托比-马奎尔33 分钟前
ES6变量与解构:let、const与模板字符串全解析
javascript
水煮白菜王1 小时前
从零搭建 React 工程化项目
前端·javascript·react.js
mosen8682 小时前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
weixin_516875654 小时前
力扣 30 天 JavaScript 挑战 第37天 第九题笔记 知识点: 剩余参数,拓展运算符
javascript·笔记·leetcode