欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用node.JS中的url模块解析URL信息

程序员文章站 2022-11-16 10:27:29
在http部分,详细介绍了url的相关知识。而nodejs中的url模块提供了一些实用函数,用于url处理与解析。解析url解析 url 对象有以下内容,依赖于他们是否在 url 字符串里存在。任何不...

在http部分,详细介绍了url的相关知识。而nodejs中的url模块提供了一些实用函数,用于url处理与解析。

解析url

解析 url 对象有以下内容,依赖于他们是否在 url 字符串里存在。任何不在 url 字符串里的部分,都不会出现在解析对象里

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

┌─────────────────────────────────────────────────────────────────────────────┐

│                                    href                                     │

├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤

│ protocol ││   auth    │      host       │           path            │ hash  │

│          ││           ├──────────┬──────┼──────────┬────────────────┤       │

│          ││           │ hostname │ port │ pathname │     search     │       │

│          ││           │          │      │          ├─┬──────────────┤       │

│          ││           │          │      │          │ │    query     │       │

"  http:   // user:pass @ host.com : 8080   /p/a/t/h  ?  query=string   #hash "

│          ││           │          │      │          │ │              │       │

└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘

href: 准备解析的完整的 url,包含协议和主机(小写)

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

protocol: 请求协议, 小写

'http:'

slashes: 协议要求的斜杠(冒号后)

true 或 false

host: 完整的 url 小写 主机部分,包含端口信息

'host.com:8080'

auth: url 中的验证信息

'user:pass'

hostname: 域名中的小写主机名

'host.com'

port: 主机的端口号

'8080'

pathname: url 中的路径部分,在主机名后,查询字符前,包含第一个斜杠

'/p/a/t/h'

search: url 中的查询字符串,包含开头的问号

'?query=string'

path: pathname 和 search 连在一起

'/p/a/t/h?query=string'

query: 查询字符串中得参数部分,或者使用 querystring.parse() 解析后返回的对象

'query=string' or {'query':'string'}

hash: url 的 “#” 后面部分(包括 # 符号)

'#hash'

url方法

url模块包含分析和解析 url 的工具。调用 require('url') 来访问模块

var url = require('url');
/*
{ parse: [function: urlparse],
 resolve: [function: urlresolve],
 resolveobject: [function: urlresolveobject],
 format: [function: urlformat],
 url: [function: url] }
 */
console.log(url);
url.parse(urlstr[, parsequerystring][, slashesdenotehost])

输入 url 字符串,返回一个对象

第二个参数parsequerystring(默认为false),如为false,则urlobject.query为未解析的字符串,比如author=%e5%b0%8f%e7%81%ab%e6%9f%b4,且对应的值不会decode;如果parsequerystring为true,则urlobject.query为object,比如{ author: '小火柴' },且值会被decode

第三个参数slashesdenotehos(默认为false),如果为true,可以正确解析不带协议头的url,类似//foo/bar里的foo就会被认为是hostname;如果为false,则foo被认为是pathname的一部分

var url = require('url');
var str = 'http://user:pass@host.com:8080/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4#hash';
/*
url {
 protocol: 'http:',
 slashes: true,
 auth: 'user:pass',
 host: 'host.com:8080',
 port: '8080',
 hostname: 'host.com',
 hash: '#hash',
 search: '?author=%e5%b0%8f%e7%81%ab%e6%9f%b4',
 query: 'author=%e5%b0%8f%e7%81%ab%e6%9f%b4',
 pathname: '/p/a/t/h',
 path: '/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4',
 href: 'http://user:pass@host.com:8080/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4#hash' }
 */
console.log(url.parse(str));
var url = require('url');
var str = 'http://user:pass@host.com:8080/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4#hash';
/*
url {
 protocol: 'http:',
 slashes: true,
 auth: 'user:pass',
 host: 'host.com:8080',
 port: '8080',
 hostname: 'host.com',
 hash: '#hash',
 search: '?author=%e5%b0%8f%e7%81%ab%e6%9f%b4',
 query: { author: '小火柴' },
 pathname: '/p/a/t/h',
 path: '/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4',
 href: 'http://user:pass@host.com:8080/p/a/t/h?author=%e5%b0%8f%e7%81%ab%e6%9f%b4#hash' }
 */
console.log(url.parse(str,true));
var url = require('url');
var str = '//foo/bar';
var result1 = url.parse(str,true);
var result2 = url.parse(str,true,true);
console.log(result1.path);//'//foo/bar'
console.log(result1.pathname);//'//foo/bar'
console.log(result1.hostname);//null
console.log(result2.path);//'/bar'
console.log(result2.pathname);//'/bar'
console.log(result2.hostname);//'foo'

url.format(urlobject)

url.parse(str)的反向操作,输入一个解析过的 url 对象,返回格式化过的字符串

urlobject包含了很多字段,比如protocol、slashes、protocol等,且不一定需要全部传,所以有一套解析逻辑

格式化的工作流程如下

href 会被忽略

protocol 无论是否有末尾的 : (冒号),会同样的处理

http, https, ftp, gopher, file 协议会被添加后缀://

mailto, xmpp, aim, sftp, foo, 等协议添加后缀:

slashes 如果协议需要 ://,设置为 true

仅需对之前列出的没有斜杠的协议,比如议 mongodb://localhost:8000/

auth 如果出现将会使用.

hostname 仅在缺少 host 时使用

port 仅在缺少 host 时使用

host 用来替换 hostname 和 port

pathname 无论结尾是否有 / 将会同样处理

search 将会替代 query属性

无论前面是否有 / 将会同样处理

query (对象; 参见 querystring) 如果没有 search,将会使用

hash 无论前面是否有#,都会同样处理

var url = require('url');
var obj = {
 protocol: 'http:',
 auth: 'user:pass',
 host: 'host.com:8080',
 hash: '#hash',
 query: { author: '小火柴' }
}
//http://user:pass@host.com:8080?author=%e5%b0%8f%e7%81%ab%e6%9f%b4#hash
console.log(url.format(obj));

url.resolve(from, to)

url.resolve()方法以一种浏览器解析超链接的方式把一个目标url解析成相对于一个基础url,参数如下

from <string> 解析时相对的基本 url。

to <string> 要解析的超链接 url。

var url = require('url');
console.log(url.resolve('/one/two/three', 'four'));     // '/one/two/four'
console.log(url.resolve('http://example.com/', '/one'));  // 'http://example.com/one'
console.log(url.resolve('http://example.com/one', '/two')); // 'http://example.com/two'