在处理 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 │
module.exports = {// Original APIUrl,parse: urlParse,resolve: urlResolve,resolveObject: urlResolveObject,format: urlFormat,// WHATWG APIURL,URLSearchParams,domainToASCII,domainToUnicode,// UtilitiespathToFileURL,fileURLToPath,urlToHttpOptions,};
URL 类
Node.js 中的 URL 类和 浏览器 URL API  完全兼容,可以通过 require('url').URL 使用,也可以使用全局变量 URL 
console.log(URL === require('url').URL); // true
new URL(input[, base]):实例化一个 URL 对象
- input:要解析的绝对或相对的 URL。
- 如果 
input是相对路径,则需要base - 如果 
input是绝对路径,则忽略base 
 - 如果 
 - 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:xyz@example.com');console.log(myURL.username); // abcmyURL.username = '123';console.log(myURL.href); // https://123:xyz@example.com/
解析 url 的文件名可以结合 path 模块
const path = require('path');const { pathname } = new URL('/foo/bar.txt', 'https://example.org/');console.log(path.basename(pathname)); // bar.txtconsole.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])```javascript 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 ```
