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

2020-06-17 08:01:32易采站长站整理

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));