Node.js学习之地址解析模块URL的使用详解(2)
第三个参数对比
例子如下:
const url = require("url");
var urlstr = "//foo/bar ";
console.log(
url.parse(urlstr, true,true)
)
/*
输出:Url {
protocol: null,
slashes: true,
auth: null,
host: 'foo',
port: null,
hostname: 'foo',
hash: null,
search: '',
query: {},
pathname: '/bar',
path: '/bar',
href: '//foo/bar' }
*/
const url = require("url");
var urlstr = "//foo/bar ";
console.log(
url.parse(urlstr)
)
/*
输出:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '//foo/bar',
path: '//foo/bar',
href: '//foo/bar' }
*/
url模块化
将一个url对象转换成一个url字符串,url对象中的属性为url.parse()产生的对象的属性。
url.parse()和url.format()互为逆操作。
例子如下:
const url = require("url");
var Urlobj = {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:8888',
port: '8888',
hostname: 'localhost',
hash: null,
search: '?name=bigbear&memo=helloworld&memo=helloC',
query: { name: 'bigbear', memo: [ 'helloworld', 'helloC' ] },
pathname: '/bb',
path: '/bb?name=bigbear&memo=helloworld&memo=helloC',
}
console.log(
url.format(Urlobj)
)
//输出:http://localhost:8888/bb?name=bigbear&memo=helloworld&memo=helloC
路径解析:url.resolve(from, to)
url.resolve()方法解决了目标URL相对于基本URL的方式类似于Web浏览器解决锚标记href。
官方手册例子:
url.resolve('/one/two/three', 'four');
// '/one/two/four'
url.resolve('http://example.com/', '/one');
// 'http://example.com/one'
url.resolve('http://example.com/one', '/two');
// 'http://example.com/two'
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对黑区网络的支持。
