Skip to content

nodeURL API 包含两部分:

  • The WHATWG URL API:该规范与 web 浏览器规范一致。(new URL()new URLSearchParams()
  • The legacy URL API

WHATWG URL Standard

js
// const { URL } = require('node:url')
const newUrl =
  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash')

const url = require('node:url')
const legacyUrl =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash')

console.log(newUrl)

console.log(legacyUrl)

1.URL

js
const { URL, URLSearchParams } = require('url')

const myURL = new URL('https://example.com:8080/path/name?query=string#hash')
/*
URL {
  href: 'https://example.com:8080/path/name?query=string#hash',
  origin: 'https://example.com:8080',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'example.com:8080',
  hostname: 'example.com',
  port: '8080',
  pathname: '/path/name',
  search: '?query=string',
  searchParams: URLSearchParams { 'query' => 'string' },
  hash: '#hash'
}
*/
console.log(myURL)

// 可以直接修改 URL 对象的属性:
myURL.pathname = '/new/path'
myURL.search = '?new=query'
console.log(myURL.href)  // 'https://example.com:8080/new/path?new=query#hash'

// 相对url
const base = new URL('https://example.com/path/')
const relative = new URL('subpath', base)
console.log(relative.href) // 'https://example.com/path/subpath'

// 序列化 URL 对象为字符串
const serializedURL = myURL.toString()
console.log(serializedURL)

// 反序列化字符串为 URL 对象
const parsedURL = new URL(serializedURL)
console.log(parsedURL.hostname)

2.URLSearchParams

js
// URLSearchParams 对象提供了处理查询字符串的便捷方法
const { URL } = require('node:url')
const myURL = new URL('https://example.com:8080/path/name?query=string#hash')
const params = new URLSearchParams(myURL.search)

console.log(params)
params.append('foo', 'bar')
console.log(params.toString()) // 'query=string&foo=bar'

params.set('query', 'newstring')
console.log(params.toString()) // 'query=newstring&foo=bar'

params.delete('foo')
console.log(params.toString()) // 'query=newstring'

console.log(params.get('query')) // 'newstring'
console.log(params.has('query')) // true
console.log(params.has('foo'))   // false

3.legacy

js
const url = require('url')

// 解析 URL
const parsedUrl = url.parse('https://example.com:8080/path/name?query=string#hash')
console.log(parsedUrl)

// 格式化 URL 对象为字符串
const formattedUrl = url.format(parsedUrl)
console.log(formattedUrl)