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

URL 规范

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

  1. " https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
  2. hostname port
  3. ├─────────────────┴──────┤
  4. protocol username password host
  5. ├──────────┴──┼──────────┴──────────┼────────────────────────┤
  6. origin origin pathname search hash
  7. ├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
  8. href
  1. module.exports = {
  2. // Original API
  3. Url,
  4. parse: urlParse,
  5. resolve: urlResolve,
  6. resolveObject: urlResolveObject,
  7. format: urlFormat,
  8. // WHATWG API
  9. URL,
  10. URLSearchParams,
  11. domainToASCII,
  12. domainToUnicode,
  13. // Utilities
  14. pathToFileURL,
  15. fileURLToPath,
  16. urlToHttpOptions,
  17. };

URL 类

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

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

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

  1. input:要解析的绝对或相对的 URL。
    1. 如果 input 是相对路径,则需要 base
    2. 如果 input 是绝对路径,则忽略 base
  2. base:如果 input 不是绝对路径,则为要解析的基础地址
    1. 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 实例中读取,也可以对属性进行修改

  1. const myURL = new URL('https://abc:xyz@example.com');
  2. console.log(myURL.username); // abc
  3. myURL.username = '123';
  4. console.log(myURL.href); // https://123:xyz@example.com/

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

  1. const path = require('path');
  2. const { pathname } = new URL('/foo/bar.txt', 'https://example.org/');
  3. console.log(path.basename(pathname)); // bar.txt
  4. 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]) ```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 ```