1. Opening analysis
This article talks about these three modules together because they are not very long in length, and secondly, there are dependencies between them, so they are introduced and analyzed in sequence. I won't say much nonsense, please see the following document:
(1), "Url module"
Let me have a little chestnut:
The code copy is as follows:
var url = require('url');
var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
console.log(typeof url.parse(queryUrl));
console.log(url.parse(queryUrl));
Running results:
The code copy is as follows:
object // typeof
{
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:8888',
port: '8888',
hostname: 'localhost',
hash: null,
search: '?name=bigbear&memo=helloworld',
query: 'name=bigbear&memo=helloworld',
pathname: '/bb',
path: '/bb?name=bigbear&memo=helloworld',
href: 'http://localhost:8888/bb?name=bigbear&memo=helloworld'
}
Explain as follows:
protocol: request protocol
host: The URL host name has been converted to lowercase, including port information
auth: The authentication information part of the URL
hostname: The hostname part of the host, converted to lowercase
port: the port number part of the host
pathname: The path part of the URL, located after the host name before the query is requested
search: The query string section of the URL, including the question mark at the beginning.
path: pathname and search are connected.
query: query the parameter part (part of the string after the question mark), or use querystring.parse() to parse the object returned.
hash: The following part of the URL "#" (including the # symbol)
Supplementary api: "url.format(urlObj)"
Function: Enter a URL object to return the formatted URL string.
(2), "QueryString module"
The "QueryString" module is used to convert URL parameter strings and parameter objects into each other, as shown below:
The code copy is as follows:
var url = require('url');
var qs = require('querystring');
var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
queryUrl = url.parse(queryUrl).query;
console.log(queryUrl);
console.log(qs.parse(queryUrl));
The operation results are as follows:
The code copy is as follows:
name=bigbear&memo=helloworld
{
name: 'bigbear',
memo: 'helloworld'
}
Supplementary API:
querystring.stringify(obj, [sep], [eq])-----Serialize an object to a query string.
You can choose whether to override the default splitter ('&') and allocator ('=').
querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')// Return the following string 'foo:bar;baz:qux'
querystring.parse(str, [sep], [eq], [options])-----Deserialize a query string into an object. You can choose whether to override the default splitter ('&') and allocator ('=').
The options object may contain a maxKeys attribute (default is 1000), which can be used to limit the number of processed keys. Setting it to 0 can remove the number of keys.
Example: querystring.parse('foo=bar&baz=qux&baz=quux&corge') // { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
(3), "Path module"
This module contains a set of tools for processing and converting file paths. Almost all methods only convert strings, and the file system will not check whether the path is true or not.
Let's first have a simple chestnut:
The code copy is as follows:
var url = require('url');
var qs = require('querystring');
var path = require("path");
var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
var root = path.basename(queryUrl);
console.log(root) ; // bb?name=bigbear&memo=helloworld
Returns the last part of the path, split with "/"
The code copy is as follows:
var url = require('url');
var qs = require('querystring');
var path = require("path");
var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
var root = path.basename(queryUrl);
console.log(root) ; // bb?name=bigbear&memo=helloworld
var ext = path.extname(root);
console.log(ext || "Not Ext Name !") ; // Not Ext Name !
Due to too many APIs, only a few commonly used ones are listed above, and everyone needs to read the document carefully.
2. Comprehensive chestnut
Scenario description----The server receives requests from different situations and performs different processing through "Url". The code is as follows:
(1), create "index.html"
The code copy is as follows:
<!doctype html>
<html>
<head>
<title>Bigbear</title>
<meta content="IE=8" http-equiv="X-UA-Compatible"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
div {
margin-top: 50px;
width: 100%;
margin: 0px;
height:120px;
line-height:120px;
color:#ffff;
font-size:22px;
background:#ff9900;
text-align: center;
}
</style>
<script src="index.js"></script>
</head>
<body>
<div>Hello, Big Bear! </div>
</body>
</html>
(2), create "index.js"
alert("Hello bb !"); // Just one sentence of code to test
(3) Create "server.js"
The code copy is as follows:
var http = require("http");
var fs = require('fs');
var url = require('url');
var path = require("path");
http.createServer(function(request,response) {
var method = request.method ;
method = method.toLowerCase();
var fileName = path.basename(request.url);
var extName = path.extname(fileName);
var root = "./" ;
if("get" == method){
if(extName){
fs.readFile("./" + fileName,"utf-8",function (error,data){
if(error)throw error ;
response.writeHead(200,{
"Content-Type": {
".css": "text/css",
".js" : "application/javascript"
}[extName]
}) ;
response.write(data);
response.end() ;
});
}
else{
fs.readFile(root + "index.html","utf-8",function (error,data){
if(error)throw error ;
response.writeHead(200,{
"Content-Type" : "text/html"
});
response.write(data);
response.end() ;
});
}
}
else if("post" == request.url){
// handle post here
}
}).listen(8888);
console.log("Web Server Running, Port On ---> 8888");
Run node server.js.
Three, let's summarize
(1) Understand the connection between the above three modules and use them flexibly.
(2) Proficient in using the three modules related APIs "Url, QueryString, and Path".
(3), and finally emphasize: understand the code intention in the above example, constantly refactor and summarize.