Skip to content

URL

Node.js 优先使用标准 URLURLSearchParams。遗留的 url.parse()url.format()url.resolve() 不用于新代码。

js
const url = new URL('https://example.com:8080/search?q=node#result')

url.hostname // example.com
url.port // 8080
url.pathname // /search
url.searchParams.get('q') // node

url.searchParams.set('page', '2')
url.toString()

URL 与文件路径互转

不要手动替换 file:// 或编码字符。使用专用 API,才能正确处理 Windows 盘符、空格和 Unicode:

js
import { fileURLToPath, pathToFileURL } from 'node:url'

const filePath = fileURLToPath(import.meta.url)
const fileUrl = pathToFileURL(filePath)

查询参数

URLSearchParams 会进行必要的编码。构造请求 URL 时不要拼接未经编码的用户输入;参数有多个值时使用 append()getAll()

基于 MIT 许可发布