parse方法将url解析为对象,第一个参数是要解析成对象的url字符串,第二个是是否查询参数,为true,查询参数解析为对象,第三个是是否以//解析主机
const path = require("path");
const url=require("url");
let str="/images/fff/123/jj.jpg";
console.log(path.parse(str));
结果:
{
root: '/',
dir: '/images/fff/123',
base: 'jj.jpg',
ext: '.jpg',
name: 'jj'
}
console.log(path.sep);// \
let u = "//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom#hash";
console.log(url.parse(u));//query
结果:
\
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: '#hash',
search: '?id=1&name=tom',
query: 'id=1&name=tom',
pathname: '//www.baidu.com:8080/images/fff/123/jj.jpg',//pathname 属性是一个可读可写的字符串,可设置或返回当前 URL 的路径部分
path: '//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom',
href: '//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom#hash'
}
console.log(url.parse(u,true));
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: '#hash',
search: '?id=1&name=tom',
query: [Object: null prototype] { id: '1', name: 'tom' },//第二个参数为true,query属性就会从查询字符串格式(“a=1&b=2”)转换为了对象格式({a: 1,b: 2})
pathname: '//www.baidu.com:8080/images/fff/123/jj.jpg',
path: '//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom',
href: '//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom#hash'
}
console.log(url.parse(u, true, true));
Url {
protocol: null,
slashes: true,
auth: null,
host: 'www.baidu.com:8080',//host
port: '8080',
hostname: 'www.baidu.com',
hash: '#hash',
search: '?id=1&name=tom',
query: [Object: null prototype] { id: '1', name: 'tom' },
pathname: '/images/fff/123/jj.jpg',
path: '/images/fff/123/jj.jpg?id=1&name=tom',
href: '//www.baidu.com:8080/images/fff/123/jj.jpg?id=1&name=tom#hash'
}