一,开篇分析
这篇文章把这三个模块拿来一起说,原因是它们各自的篇幅都不是很长,其次是它们之间存在着依赖关系,所以依次介绍并且实例分析。废话不多说了,请看下面文档:
(1),\"Url模块\"
来个小栗子:
http://localhost:8888/bb?name=bigbear&memo=helloworld\" ;
console.log(typeof url.parse(queryUrl)) ;
console.log(url.parse(queryUrl)) ;
运行结果:
http://localhost:8888/bb?name=bigbear&memo=helloworld\" ;
queryUrl = url.parse(queryUrl).query ;
console.log(queryUrl) ;
console.log(qs.parse(queryUrl)) ;
运行结果·如下:
http://localhost:8888/bb?name=bigbear&memo=helloworld\" ;
var root = path.basename(queryUrl) ;
console.log(root) ; // bb?name=bigbear&memo=helloworld
返回路径中的最后一部分,以”/“分割。
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 !
由于api过多,以上只列出来了常用的几个,大家需认真阅读文档。
二,综合栗子
场景描述------服务器接到不同情况的请求,通过 “Url” 分别做不同处理,代码如下:
(1),建立”index.html“
<!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:#fff;
font-size:22px;
background:#ff9900;
text-align: center;
}
</style>
<script src=\"index.js\"></script>
</head>
<body>
<div>Hello,大熊!</div>
</body>
</html>
(2),建立”index.js“
alert(\"Hello bb !\") ; // 为了测试就这么一句代码
(3),建立”server.js“
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\") ;
node server.js 运行一下。
三,总结一下
(1),理解上述三个模块之间的联系,灵活使用 。
(2),熟练使用 \"Url,QueryString,Path\" 三个模块相关的api。
(3),最后强调:理解上面例子中的代码意图,不断重构,不断总结。