url模块
处理HTTP请求时url模块使用率超高,因为该模块允许解析URL、生成URL,以及拼接URL。首先我们来看看一个完整的URL的各组成部分。
href
-----------------------------------------------------------------
host path
--------------- ----------------------------
http: // user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash
----- --------- -------- ---- -------- ------------- -----
protocol auth hostname port pathname search hash
------------
query
url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash');
http.createServer(function (request, response) {
var tmp = request.url; // => "/foo/bar?a=b"
url.parse(tmp);
}).listen(80);
反过来,format方法允许将一个URL对象转换为URL字符串,示例如下。
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
url.resolve('http://www.example.com/foo/bar', '../baz');
querystring模块用于实现URL参数字符串与参数对象的互相转换,示例如下。
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });