12

极简 Node.js 入门 - 5.2 url & querystring

 3 years ago
source link: https://www.cnblogs.com/dolphinX/p/13818602.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node

本文更佳阅读体验:https://www.yuque.com/sunluyong/node/url-qs

在处理 web 信息的时候经常需要解析 url,Node.js 提供了方便的处理模块

URL 规范

URL 全称是 uniform resource locator,统一资源定位符,根据一个 url 能够在全球确定一个唯一的资源,URL 由不同的字段组成,url 模块提供了两套 API 来处理 URL:一个是旧版本遗留的 API,一个是实现了 WHATWG标准的新 API。为了避免混淆,下文只介绍目前通用的 WHATWG 标准

"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          │  │          │          │    hostname     │ port │          │                │       │
│          │  │          │          ├─────────────────┴──────┤          │                │       │
│ protocol │  │ username │ password │          host          │          │                │       │
├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
│   origin    │                     │         origin         │ pathname │     search     │ hash  │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│                                              href                                              │

Node.js 中的 URL 类和浏览器 URL API 完全兼容,可以通过 require('url').URL 使用,也可以使用全局变量 URL

console.log(URL === require('url').URL); // true

new URL(input[, base]):实例化一个 URL 对象

  1. input:要解析的绝对或相对的 URL。如果 input 是相对路径,则需要 base;如果 input 是绝对路径,则忽略 base
  2. base:如果 input 不是绝对路径,则为要解析的基础地址
const myURL = new URL('/foo', 'https://example.org/'); // https://example.org/foo

URL 实例属性

  • url.hash
  • url.host
  • url.hostname
  • url.href
  • url.origin
  • url.password
  • url.pathname
  • url.port
  • url.protocol
  • url.search
  • url.serachParam
  • url.username

URL 规范中的所有字段都可以从 URL 实例中读取,也可以对属性进行修改

const myURL = new URL('https://abc:[email protected]');
console.log(myURL.username); // abc

myURL.username = '123';
console.log(myURL.href); // https://123:[email protected]/

解析 url 的文件名可以结合 path 模块

const path = require('path');

const { pathname } = new URL('/foo/bar.txt', 'https://example.org/');

console.log(path.basename(pathname)); // bar.txt
console.log(path.parse(pathname));

querystring

URL 实例中返回的 search 是querystring 的完整字符串,并不是键值对的格式,对 querystring 操作可以使用 url.serachParam 属性,该属性是 URLSearchParams 类实例,同时也是个迭代器,有几个常用的方法操作 querystring

  • urlSearchParams.get(name)
  • urlSearchParams.set(name, value)
  • urlSearchParams.delete(name)
  • urlSearchParams.append(name, value)
  • urlSearchParams.forEach(fn[, thisArg])

使用都非常简单

const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc')); // 123

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href); // https://example.org/?abc=123&abc=xyz

myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href); // https://example.org/?a=b

在较早的版本使用 Node.js 内置模块 querystring 来操作 url querystring,简单场景可以不再使用


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK