JavaScript大全

nodejs url模块详解

2016-04-10  本文已影响617人  nummycode

个人原创,如需转载,请联系作者

URL模块用于解析和处理URL字符串,提供了三个方法:

parse方法

将URL解析成一下几部分:

示例:

var url = require("url")
var myurl="http://www.nodejs.org/some/url/?with=query&param=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&param=that',
  query: 'with=query&param=that',
  pathname: '/some/url/',
  path: '/some/url/?with=query&param=that',
  href: 'http://www.nodejs.org/some/url/?with=query&param=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&param=that',
  query: { with: 'query', param: 'that' },
  pathname: '/some/url/',
  path: '/some/url/?with=query&param=that',
  href: 'http://www.nodejs.org/some/url/?with=query&param=that#about' }
> 

format方法

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&param=that',
...   query: { with: 'query', param: 'that' },
...   pathname: '/some/url/',
...   path: '/some/url/?with=query&param=that',
...   href: 'http://www.nodejs.org/some/url/?with=query&param=that#about' }
undefined
> output=url.format(urlObj)
'http://www.nodejs.org/some/url/?with=query&param=that#about'

resolve方法

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'
上一篇下一篇

猜你喜欢

热点阅读