网址字符串是包含多个有意义组件的结构化字符串。 解析时,将返回包含每个组件的属性的网址对象。

    1. var log4js = require('log4js')
    2. log4js.configure({
    3. appenders: { cheese: { type: "file", filename: "cheese.log" } },
    4. categories: { default: { appenders: ["cheese"], level: "error" } }
    5. });
    6. const logger = log4js.getLogger("cheese");
    7. logger.level = 'debug'
    8. const url = require('url')
    9. const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
    10. const urlObj = {
    11. protocol: 'https:',
    12. slashes: true,
    13. auth: null,
    14. host: 'www.baidu.com:443',
    15. port: '443',
    16. hostname: 'www.baidu.com',
    17. hash: '#tag=110',
    18. search: '?id=8&name=mouse',
    19. query: 'id=8&name=mouse',
    20. pathname: '/ad/index.html',
    21. path: '/ad/index.html?id=8&name=mouse',
    22. href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
    23. }
    24. // logger.debug(url.parse(urlString))
    25. // logger.debug(url.format(urlObj))
    26. // logger.debug(url.resolve('http://www.abc.com/a', '../'))
    27. // logger.debug(url.resolve('http://www.abc.com/a', '/b'))
    28. // const urlParams = new URLSearchParams(urlString)
    29. // logger.debug(urlParams)
    30. const urlParams2 = new URLSearchParams(url.parse(urlString).search)
    31. logger.debug(urlParams2.get('id'))

    log文档

    1. [2021-07-06T13:51:12.050] [DEBUG] cheese - Url {
    2. protocol: 'https:',
    3. slashes: true,
    4. auth: null,
    5. host: 'www.baidu.com:443',
    6. port: '443',
    7. hostname: 'www.baidu.com',
    8. hash: '#tag=110',
    9. search: '?id=8&name=mouse',
    10. query: 'id=8&name=mouse',
    11. pathname: '/ad/index.html',
    12. path: '/ad/index.html?id=8&name=mouse',
    13. href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
    14. }
    15. [2021-07-06T13:52:19.429] [DEBUG] cheese - https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110
    16. [2021-07-06T13:52:19.432] [DEBUG] cheese - http://www.abc.com/
    17. [2021-07-06T13:52:19.432] [DEBUG] cheese - http://www.abc.com/b
    18. [2021-07-06T13:53:02.360] [DEBUG] cheese - URLSearchParams { 'https://www.baidu.com:443/ad/index.html?id' => '8', 'name' => 'mouse#tag=110' }
    19. [2021-07-06T14:06:08.179] [DEBUG] cheese - 8