URL Module
URL module usage is very high when processing HTTP requests because the module allows URLs to be parsed, URLs to be generated, and stitching URLs. First, let's look at a complete URL for each component.
Copy Code code as follows:
Href
-----------------------------------------------------------------
Host Path
--------------- ----------------------------
http://User:pass @ host.com:8080/p/a/t/h query=string #hash
----- --------- -------- ---- -------- ------------- -----
Protocol auth hostname Port Pathname Search Hash
------------
Query
We can use the. Parse method to convert a URL string to a URL object, as shown below.
Copy Code code 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 '}
*/
Pass to the. Parse method is not necessarily a complete URL, for example, in the HTTP server callback function, Request.url does not contain the protocol header and domain name, but can also be resolved using the. Parse method.
Copy Code code as follows:
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 optional arguments for the second and third Boolean types. When the second argument equals True, the query field in the URL object returned by the method is no longer a string, but rather a parameter object after the QueryString module has been converted. When the third argument equals True, the method correctly resolves URLs without protocol headers, such as//www.example.com/foo/bar.
In turn, the Format method allows a URL object to be converted to a URL string, as shown below.
Copy Code code 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.
Copy Code code as follows:
Url.resolve (' Http://www.example.com/foo/bar ', '. /baz ');
/* =>
Http://www.example.com/baz
*/
Query String
The QueryString module is used to convert the URL parameter string to and from the Parameter object, as shown below.
Copy Code code 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= '
*/