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

1、URL类

url模块在v16的nodejs中已经明确被废弃,在将来的升级node中,可能被不支持。
官网建议在废弃url、querystring模块后,采用URL类去替代

1.1、图示 URL 各部分

在这里插入图片描述

1.2、旧版的url模块(node16之前版本)

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

const url = require('url');

常用的方法

  1. parse(urlString[, parseQueryString[, slashesDenoteHost]]):将一个 URL 字符串解析成一个 URL 对象。
  2. format(urlObject):将一个 URL 对象格式化成一个 URL 字符串。
  3. resolve(from, to):解析一个相对路径,返回完整的 URL 字符串。
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
hostURL主机名,包括端口信息,小写‘host.com:8080’
authURL中的认证信息‘user:pass’
hostname主机名,小写‘host.com’
port主机的端口号‘8080’
pathnameURL中路径‘/p/a/t/h’
search查询对象,即:queryString,包括之前的问号“?”‘?query=string’
pathpathname 和 search的合集‘/p/a/t/h?query=string’
query查询字符串中的参数部分(问号后面部分字符串)‘query=string’ or {‘query’:‘string’}
hash锚点部分(即:“#”及其后的部分)‘#hash’

1.3、新版的url模块(node16版本之后)

注意点:在v16及以上中,nodejs已经废弃了url/querystring模块需要被URL类给替代

语法:newURL(path[,baseUrl])

  • path:需要被URL类解析的路径
  • baseUrl:主机名,如果path中已经带有域名,则baseUrl可以不写

URL类不是模块,不需要导入

1、创建URL对象

const { URL } = require('url');

const myUrl = new URL('https://www.example.com/path/?query=value');
console.log(myUrl);

// Output: URL {
//   href: 'https://www.example.com/path/?query=value',
//   origin: 'https://www.example.com',
//   protocol: 'https:',
//   username: '',
//   password: '',
//   host: 'www.example.com',
//   hostname: 'www.example.com',
//   port: '',
//   pathname: '/path/',
//   search: '?query=value',
//   searchParams: URLSearchParams { 'query' => 'value' },
//   hash: ''
// }

2、获取 URL 的各个部分

console.log(myUrl.protocol); // return: 'https:'
console.log(myUrl.host); // return: 'www.example.com'
console.log(myUrl.pathname); // return: '/path/'
console.log(myUrl.search); // return: '?query=value'
console.log(myUrl.hash); // return: ''

3、修改 URL 的各个部分

myUrl.hash = 'section1';
console.log(myUrl.href); 
// return: 'https://www.example.com/path/?query=value#section1'

4、new URLSearchParams

new URLSearchParams()是Web API中的一个构造函数,用于创建一个表示URL查询参数的对象

它可以接受一个查询字符串作为参数,也可以通过键值对、数组、对象等方式来添加查询参数。

该对象可以轻松地对查询参数进行增删改查,方便进行URL的构造和解。

现在常被用来当做 替代queryString 板块。

const params = new URLSearchParams('?name=Lucy&age=18');

console.log(params.has('name')); // true
console.log(params.get('age')); // 18
console.log(params.toString()); // 'name=Lucy&age=18'

params.set('gender', 'female');
console.log(params.toString()); // 'name=Lucy&age=18&gender=female'

2、queryString 模块(node16版本之前)

作用:查询字符串主要由两个方法和内置格式化方法组成,一个是将对象转换为字符串,一个则是相反,将字符串转换为对象:

方法描述
querystring.stringify(obj, [sep], [eq])将JSON对象格式化为查询字符串格式的字符串
querystring.parse(str, [sep], [eq], [options])根据“&”和“=”将字符串进行分割,反序列化为JSON对象

1、stringify

作用: 对象转为query字符串

将JSON对象格式化为查询字符串格式的字符串,默认的分隔符为:“&”和“=”,具体可以看一下以下代码:

const querystring=require('querystring')

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns
'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
// returns
'foo:bar;baz:qux'

对象转为query字符串

const querystring=require('querystring')

querystring.stringify({foo:'bar',abc:'xyz'})
querystring.encode({foo:'bar',abc:'xyz'})

//foo=bar&abc=xyz
//foo=bar&abc=xyz

2、parse

作用:将query字符串转为对象

根据“&”和“=”将字符串进行分割,反序列化为JSON对象,而options包含的maxKeys默认设置为1000,如果将其设置为0则表示没这个限制。

const querystring=require('querystring')

querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

将query字符串转为对象

const querystring=require('querystring')

//query字符串转为对象
querystring.parse('foo=bar&abc=xyz')
querystring.decode('foo=bar&abc=xyz')

//{ foo: 'bar', abc: 'xyz' }
// { foo: 'bar', abc: 'xyz' }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值