url module
The url module is highly used when processing HTTP requests, because this module allows parsing URLs, generating URLs, and splicing URLs. First let's take a look at the components of a complete URL.
href
-------------------------------------------------- ---------------
host path
---------------------------------------------------------------------------------------------------------------
http: // user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash
----- --------- -------- ---- -------- ------------- --- --
protocol auth hostname port pathname search hash
Since
query
We can use the .parse method to convert a URL string into a URL object. The example is as follows.
url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash');
/* =>
{ protocol: 'http:',
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/p/a/t/h',
path: '/p/a/t/h?query=string',
href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' }
*/
What is passed to the .parse method does not have to be a complete URL. For example, in the HTTP server callback function, request.url does not contain the protocol header and domain name, but it can also be parsed using the .parse method.
http.createServer(function (request, response) {
var tmp = request.url; // => "/foo/bar?a=b"
url.parse(tmp);
/* =>
{ protocol: null,
slashes: null,
auth: null,
Host: null,
Port: null,
Hostname: null,
hash: null,
Search: '?a=b',
Query: 'a=b',
Pathname: '/foo/bar',
Path: '/foo/bar?a=b',
href: '/foo/bar?a=b' }
*/
}).listen(80);
The .parse method also supports second and third optional parameters of type Boolean. When the second parameter is equal to true, in the URL object returned by this method, the query field is no longer a string, but a parameter object converted by the querystring module. When the third parameter is equal to true, this method can correctly parse URLs without protocol headers, such as //www.example.com/foo/bar.
In turn, the format method allows converting a URL object into a URL string, as shown below.
Copy code The code is as follows:
url.format({
Protocol: 'http:',
Host: 'www.example.com',
Pathname: '/p/a/t/h',
Search: 'query=string'
});
/* =>
'http://www.example.com/p/a/t/h?query=string'
*/
In addition, the .resolve method can be used to splice URLs, as shown below.
url.resolve('http://www.example.com/foo/bar', '../baz');
/* =>
http://www.example.com/baz
*/
Query String
The querystring module is used to convert URL parameter strings and parameter objects to and from each other. The example is as follows.
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
/* =>
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
*/
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
/* =>
'foo=bar&baz=qux&baz=quux&corge='
*/