个人原创,如需转载,请联系作者
URL模块用于解析和处理URL字符串,提供了三个方法:
将URL解析成一下几部分:
示例:
var url = require("url")
var myurl="http://www.nodejs.org/some/url/?with=query¶m=that#about"
parsedUrl=url.parse(myurl)
结果如下:
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'www.nodejs.org',
port: null,
hostname: 'www.nodejs.org',
hash: '#about',
search: '?with=query¶m=that',
query: 'with=query¶m=that',
pathname: '/some/url/',
path: '/some/url/?with=query¶m=that',
href: 'http://www.nodejs.org/some/url/?with=query¶m=that#about'
}
parse方法有两个参数:url字符串与一个可选的布尔值。布尔值用来确定queryString是否要用querystring模块来解析,默认为false。 如果为true,上面的结果如下:
> parsedUrl=url.parse(myurl,true)
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'www.nodejs.org',
port: null,
hostname: 'www.nodejs.org',
hash: '#about',
search: '?with=query¶m=that',
query: { with: 'query', param: 'that' },
pathname: '/some/url/',
path: '/some/url/?with=query¶m=that',
href: 'http://www.nodejs.org/some/url/?with=query¶m=that#about' }
>
format方法与parse方法相反,它用于根据某个对象生成URL字符串。 例如:
> var urlObj={ protocol: 'http:',
... slashes: true,
... auth: null,
... host: 'www.nodejs.org',
... port: null,
... hostname: 'www.nodejs.org',
... hash: '#about',
... search: '?with=query¶m=that',
... query: { with: 'query', param: 'that' },
... pathname: '/some/url/',
... path: '/some/url/?with=query¶m=that',
... href: 'http://www.nodejs.org/some/url/?with=query¶m=that#about' }
undefined
> output=url.format(urlObj)
'http://www.nodejs.org/some/url/?with=query¶m=that#about'
resolve(from, to)方法用于拼接URL,它根据相对URL拼接成新的URL。 例如:
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'