標籤:
一,開篇分析
這篇文章把這三個模組拿來一起說,原因是它們各自的篇幅都不是很長,其次是它們之間存在著依賴關係,所以依次介紹並且執行個體分析。廢話不多說了,請看下面文檔:
(1),"Url模組"
來個小栗子:
1 var url = require(‘url‘);2 var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;3 console.log(typeof url.parse(queryUrl)) ;4 console.log(url.parse(queryUrl)) ;
運行結果:
1 object // typeof 2 3 { 4 protocol: ‘http:‘, 5 slashes: true, 6 auth: null, 7 host: ‘localhost:8888‘, 8 port: ‘8888‘, 9 hostname: ‘localhost‘,10 hash: null,11 search: ‘?name=bigbear&memo=helloworld‘,12 query: ‘name=bigbear&memo=helloworld‘,13 pathname: ‘/bb‘,14 path: ‘/bb?name=bigbear&memo=helloworld‘,15 href: ‘http://localhost:8888/bb?name=bigbear&memo=helloworld‘16 }
加以說明如下:
protocol: 請求協議
host: URL主機名稱已全部轉換成小寫, 包括連接埠資訊
auth:URL中身分識別驗證資訊部分
hostname:主機的主機名稱部分, 已轉換成小寫
port: 主機的連接埠號碼部分
pathname: URL的路徑部分,位於主機名稱之後請求查詢之前
search: URL 的“查詢字串”部分,包括開頭的問號。
path: pathname 和 search 連在一起。
query: 查詢字串中的參數部分(問號後面部分字串),或者使用 querystring.parse() 解析後返回的對象。
hash: URL 的 “#” 後面部分(包括 # 符號)
補充api:"url.format(urlObj)"
作用:輸入一個 URL 對象,返回格式化後的 URL 字串。
(2),"QueryString模組"
"QueryString" 模組用於實現URL參數字串與參數對象的互相轉換,來個栗子,如下所示:
1 var url = require(‘url‘);2 var qs = require(‘querystring‘);3 var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;4 queryUrl = url.parse(queryUrl).query ;5 console.log(queryUrl) ;6 console.log(qs.parse(queryUrl)) ;
運行結果·如下:
name=bigbear&memo=helloworld
{
name: ‘bigbear‘,
memo: ‘helloworld‘
}
補充api:
querystring.stringify(obj, [sep], [eq])------序列化一個對象到一個 query string。
可以選擇是否覆蓋預設的分割符(‘&‘)和分配符(‘=‘)。
querystring.stringify({foo: ‘bar‘, baz: ‘qux‘}, ‘;‘, ‘:‘)// 返回如下字串‘foo:bar;baz:qux‘
querystring.parse(str, [sep], [eq], [options])------將一個 query string 還原序列化為一個對象。可以選擇是否覆蓋預設的分割符(‘&‘)和分配符(‘=‘)。
options對象可能包含maxKeys屬性(預設為1000),它可以用來限制處理過的鍵(key)的數量.設為0可以去除鍵(key)的數量限制.
樣本:querystring.parse(‘foo=bar&baz=qux&baz=quux&corge‘) // { foo: ‘bar‘, baz: [‘qux‘, ‘quux‘], corge: ‘‘ }
(3),"Path模組"
本模組包含一套用於處理和轉換檔路徑的工具集。幾乎所有的方法僅對字串進行轉換, 檔案系統是不會檢查路徑是否真實有效。
先來一個簡單的栗子:
1 var url = require(‘url‘);2 var qs = require(‘querystring‘);3 var path = require("path") ;4 var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;5 var root = path.basename(queryUrl) ;6 console.log(root) ; // bb?name=bigbear&memo=helloworld
返迴路徑中的最後一部分,以”/“分割。
1 var url = require(‘url‘);2 var qs = require(‘querystring‘);3 var path = require("path") ;4 var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;5 var root = path.basename(queryUrl) ;6 console.log(root) ; // bb?name=bigbear&memo=helloworld7 var ext = path.extname(root) ;8 console.log(ext || "Not Ext Name !") ; // Not Ext Name !
由於api過多,以上只列出來了常用的幾個,大家需認真閱讀文檔。
二,綜合栗子
情境描述------伺服器接到不同情況的請求,通過 “Url” 分別做不同處理,代碼如下:
(1),建立”index.html“
1 <!doctype html> 2 <html> 3 <head> 4 <title>Bigbear</title> 5 <meta content="IE=8" http-equiv="X-UA-Compatible"/> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <style type="text/css"> 8 div { 9 margin-top: 50px;10 width: 100%; 11 margin: 0px;12 height:120px;13 line-height:120px;14 color:#fff;15 font-size:22px;16 background:#ff9900;17 text-align: center;18 }19 </style>20 <script src="index.js"></script>21 </head>22 <body>23 <div>Hello,大熊!</div>24 </body>25 </html>
(2),建立”index.js“
alert("Hello bb !") ; // 為了測試就這麼一句代碼
(3),建立”server.js“
1 var http = require("http"); 2 var fs = require(‘fs‘); 3 var url = require(‘url‘); 4 var path = require("path") ; 5 http.createServer(function(request,response) { 6 var method = request.method ; 7 method = method.toLowerCase() ; 8 var fileName = path.basename(request.url) ; 9 var extName = path.extname(fileName) ;10 var root = "./" ;11 if("get" == method){12 if(extName){13 fs.readFile("./" + fileName,"utf-8",function (error,data){14 if(error)throw error ;15 response.writeHead(200,{16 "Content-Type": {17 ".css": "text/css" ,18 ".js" : "application/javascript"19 }[extName]20 }) ;21 response.write(data) ;22 response.end() ;23 });24 }25 else{26 fs.readFile(root + "index.html","utf-8",function (error,data){27 if(error)throw error ;28 response.writeHead(200,{29 "Content-Type" : "text/html"30 });31 response.write(data) ;32 response.end() ;33 });34 }35 }36 else if("post" == request.url){37 // handle post here38 }39 }).listen(8888) ;40 console.log("Web Server Running , Port On ---> 8888") ;
node server.js 運行一下。
三,總結一下
(1),理解上述三個模組之間的聯絡,靈活使用 。
(2),熟練使用 "Url,QueryString,Path" 三個模組相關的api。
(3),最後強調:理解上面例子中的代碼意圖,不斷重構,不斷總結。
哈哈哈,本篇結束,未完待續,希望和大家多多交流夠溝通,共同進步。。。。。。呼呼呼……(*^__^*)
大熊君大話NodeJS之------(Url,QueryString,Path)模組