网址字符串是包含多个有意义组件的结构化字符串。 解析时,将返回包含每个组件的属性的网址对象。
var log4js = require('log4js')
log4js.configure({
appenders: { cheese: { type: "file", filename: "cheese.log" } },
categories: { default: { appenders: ["cheese"], level: "error" } }
});
const logger = log4js.getLogger("cheese");
logger.level = 'debug'
const url = require('url')
const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
const urlObj = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=110',
search: '?id=8&name=mouse',
query: 'id=8&name=mouse',
pathname: '/ad/index.html',
path: '/ad/index.html?id=8&name=mouse',
href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
}
// logger.debug(url.parse(urlString))
// logger.debug(url.format(urlObj))
// logger.debug(url.resolve('http://www.abc.com/a', '../'))
// logger.debug(url.resolve('http://www.abc.com/a', '/b'))
// const urlParams = new URLSearchParams(urlString)
// logger.debug(urlParams)
const urlParams2 = new URLSearchParams(url.parse(urlString).search)
logger.debug(urlParams2.get('id'))
log文档
[2021-07-06T13:51:12.050] [DEBUG] cheese - Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=110',
search: '?id=8&name=mouse',
query: 'id=8&name=mouse',
pathname: '/ad/index.html',
path: '/ad/index.html?id=8&name=mouse',
href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
}
[2021-07-06T13:52:19.429] [DEBUG] cheese - https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110
[2021-07-06T13:52:19.432] [DEBUG] cheese - http://www.abc.com/
[2021-07-06T13:52:19.432] [DEBUG] cheese - http://www.abc.com/b
[2021-07-06T13:53:02.360] [DEBUG] cheese - URLSearchParams { 'https://www.baidu.com:443/ad/index.html?id' => '8', 'name' => 'mouse#tag=110' }
[2021-07-06T14:06:08.179] [DEBUG] cheese - 8