Skip to content

url 模块

url 模块用于解析、构建和格式化 URL。在 Node.js 中,URL 处理是网络编程中非常常见的任务,url 模块提供了多种方法来便捷地处理 URL。

fileURLToPath

将 URL 字符串或 URL 对象转换为文件系统路径格式。在 ESM 模块中经常用于处理 import.meta.url

js
import { fileURLToPath } from 'node:url'
import path from 'node:path'

// ESM 中获取当前文件路径
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 转换 file:// URL
fileURLToPath('file:///C:/path/file.js') // 'C:\path\file.js'
fileURLToPath('file:///home/user/file.js') // '/home/user/file.js'

URL 解析与格式化

  • url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
    解析给定的 URL 字符串,并返回一个 URL 对象。parseQueryString 是一个可选参数,默认为 false,如果为 true,则查询字符串会被解析为一个对象。slashesDenoteHost 用于指定是否将双斜杠视为 URL 主机名的标志。

    js
    const url = require('url')
    const parsedUrl = url.parse('https://example.com:8080/pathname?search=test#hash', true)
    console.log(parsedUrl)
    // {
    //   protocol: 'https:',
    //   slashes: true,
    //   auth: null,
    //   host: 'example.com:8080',
    //   port: '8080',
    //   hostname: 'example.com',
    //   hash: '#hash',
    //   search: '?search=test',
    //   query: { search: 'test' },
    //   pathname: '/pathname',
    //   path: '/pathname?search=test',
    //   href: 'https://example.com:8080/pathname?search=test#hash'
    // }
  • url.format(urlObject)
    将 URL 对象转换为字符串。返回一个有效的 URL 字符串。

    js
    const url = require('url')
    const urlObject = {
      protocol: 'https:',
      host: 'example.com',
      pathname: '/path',
      query: { key: 'value' },
    }
    const formattedUrl = url.format(urlObject)
    console.log(formattedUrl) // 'https://example.com/path?key=value'

URL 解析的对象结构

url.parse 返回的 URL 对象包含以下属性:

  • protocol: URL 的协议部分(如 'http:''https:')。
  • slashes: 布尔值,表示 URL 是否包含 //(即是否为 host)。
  • auth: 如果 URL 包含认证信息,返回 username:password 格式的字符串;否则返回 null
  • host: 包含主机名和端口号的完整主机部分。
  • hostname: 主机名部分,不包括端口。
  • port: 端口号部分(如果指定)。
  • pathname: 路径部分。
  • search: 查询字符串(以 ? 开头),如果存在。
  • query: 查询参数的对象(如果 parseQueryStringtrue)。
  • hash: 锚点部分(以 # 开头),如果存在。
  • href: 完整的 URL 字符串。

URL 查询字符串

  • url.querystring
    url 模块不直接提供方法来解析查询字符串,通常配合 querystring 模块使用。

    js
    const querystring = require('querystring')
    const parsedQuery = querystring.parse('foo=bar&baz=qux')
    console.log(parsedQuery) // { foo: 'bar', baz: 'qux' }
  • url.format() 与查询字符串
    如果 URL 对象中的 query 属性是一个对象,url.format() 会将其转换为查询字符串并附加到最终的 URL 字符串中。

    js
    const url = require('url')
    const urlObject = {
      protocol: 'https:',
      host: 'example.com',
      pathname: '/search',
      query: { query: 'node.js', page: 2 },
    }
    const formattedUrl = url.format(urlObject)
    console.log(formattedUrl) // 'https://example.com/search?query=node.js&page=2'

URL 路径和查询字符串操作

  • url.resolve(from, to)
    解析相对 URL,相对于给定的 from URL 返回一个绝对的 to URL。

    js
    const url = require('url')
    const resolvedUrl = url.resolve('http://example.com/foo/bar', '/baz')
    console.log(resolvedUrl) // 'http://example.com/baz'

使用 URL 类(Node.js v7.0.0+)

从 Node.js v7.0.0 开始,可以使用内置的 URL 类来处理 URL。这个类提供了更加简洁和现代化的 API。

  • new URL(url[, base])
    URL 类的构造函数,用于创建一个 URL 对象。第一个参数是要解析的 URL 字符串,第二个参数是可选的基 URL,用于相对路径的解析。

    js
    const { URL } = require('url')
    const myURL = new URL('path/name?query=123', 'https://example.com/')
    console.log(myURL.href) // 'https://example.com/path/name?query=123'
  • urlObject.href
    返回当前 URL 的完整字符串。

    js
    const { URL } = require('url')
    const myURL = new URL('path/name?query=123', 'https://example.com/')
    console.log(myURL.href) // 'https://example.com/path/name?query=123'
  • urlObject.hostname
    返回 URL 的主机名部分(不包括端口)。

    js
    const { URL } = require('url')
    const myURL = new URL('path/name?query=123', 'https://example.com/')
    console.log(myURL.hostname) // 'example.com'
  • urlObject.pathname
    返回 URL 的路径部分。

    js
    const { URL } = require('url')
    const myURL = new URL('path/name?query=123', 'https://example.com/')
    console.log(myURL.pathname) // '/path/name'
  • urlObject.search
    返回查询字符串(包括 ?)。

    js
    const { URL } = require('url')
    const myURL = new URL('path/name?query=123', 'https://example.com/')
    console.log(myURL.search) // '?query=123'
  • urlObject.searchParams
    返回一个 URLSearchParams 对象,用于操作查询字符串参数。

    js
    const { URL } = require('url')
    const myURL = new URL('https://example.com/path?query=123&foo=bar')
    console.log(myURL.searchParams.get('query')) // '123'
    console.log(myURL.searchParams.has('foo')) // true
    myURL.searchParams.append('baz', 'qux')
    console.log(myURL.href) // 'https://example.com/path?query=123&foo=bar&baz=qux'

基于 MIT 许可发布