内置模块url常用api

  • log4js模块用来记录日志
npm i log4js -D

log4j模块文档

  • url内置模块用来解析url地址
  1. url.parse():将url字符串地址解析为url对象
  2. url.format():将url对象解析为url字符串地址
  3. url.resolve():用来处理路径上下文
  4. URLSearchParams类接收一个参数,类似于?id=12(可以通过url.parse(location).search获取),之后通过实例对象的 get api获取参数
const 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 location = 'https://www.baidu.com:443/path/index.html?id=12#tag';

const location_obj={
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com:443',
  port: '443',
  hostname: 'www.baidu.com',
  hash: '#tag',
  search: '?id=12',
  query: 'id=12',
  pathname: '/path/index.html',
  path: '/path/index.html?id=12',
  href: 'https://www.baidu.com:443/path/index.html?id=12#tag'
}

logger.debug(url.parse(location));

logger.debug(url.format(location_obj));

logger.debug(url.resolve('http://www.abc.com/a', '../'));

logger.debug(url.resolve('http://www.abc.com/a', '/b'));

const urlParams = new URLSearchParams(url.parse(location).search);

logger.debug(urlParams.get('id'));

[2021-06-03T12:52:40.790] [DEBUG] cheese - Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com:443',
  port: '443',
  hostname: 'www.baidu.com',
  hash: '#tag',
  search: '?id=12',
  query: 'id=12',
  pathname: '/path/index.html',
  path: '/path/index.html?id=12',
  href: 'https://www.baidu.com:443/path/index.html?id=12#tag'
}
[2021-06-03T12:52:40.793] [DEBUG] cheese - https://www.baidu.com:443/path/index.html?id=12#tag
[2021-06-03T12:52:40.794] [DEBUG] cheese - http://www.abc.com/
[2021-06-03T12:52:40.794] [DEBUG] cheese - http://www.abc.com/b
[2021-06-03T12:52:40.795] [DEBUG] cheese - 12