parse() / new URL()
都是用来解析url的:
用法:
1、parse()
const url = require("url");
const urlString = "http://www.baidu.com:443/path/index.html?id=2#tag=3";
logger.debug(url.parse(urlString));
结果是这样的:
[2022-01-22T20:43:46.471] [DEBUG] cheese - Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=3',
search: '?id=2',
query: 'id=2',
pathname: '/path/index.html',
path: '/path/index.html?id=2',
href: 'http://www.baidu.com:443/path/index.html?id=2#tag=3'
}
2、new URL()
const urlString = "http://www.baidu.com:443/path/index.html?id=2#tag=3";
logger.debug(new URL(urlString));
出来是这样的:
[2022-01-22T20:43:17.041] [DEBUG] cheese - URL {
href: 'http://www.baidu.com:443/path/index.html?id=2#tag=3',
origin: 'http://www.baidu.com:443',
protocol: 'http:',
username: '',
password: '',
host: 'www.baidu.com:443',
hostname: 'www.baidu.com',
port: '443',
pathname: '/path/index.html',
search: '?id=2',
searchParams: URLSearchParams { 'id' => '2' },
hash: '#tag=3'
}
区别:parse() 是 Node.js 特定的旧版 API,new URL() 是实现了与 Web 浏览器使用的相同的 WHATWG 网址标准的新版 API