Node.js 在處理請求位址、解析參數與操作檔案路徑時,最常打交道的就是 url、querystring 與 path 這三個內建模組。它們 individually 篇幅都不長,彼此之間卻有明確的依賴關係,因此很適合放在一起理解。
url.parse() 是整個體系的核心,它能把一條完整的 URL 字串拆解成十來個語意清晰的欄位。
var url = require('url');
var queryUrl = "https://localhost:8888/bb?name=bigbear&memo=helloworld";
console.log(typeof url.parse(queryUrl)); // object
console.log(url.parse(queryUrl));
輸出結果:
{
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: 'https://localhost:8888/bb?name=bigbear&memo=helloworld'
}
querystring.parse() 解析後的物件。反過來的操作由 url.format(urlObj) 完成——傳入一個 URL 物件,回傳格式化後的 URL 字串。
顧名思義,這個模組負責在「查詢字串」與「參數物件」之間互相轉換,是 Url 模組的天然搭檔。
var url = require('url');
var qs = require('querystring');
var queryUrl = "https://localhost:8888/bb?name=bigbear&memo=helloworld";
queryUrl = url.parse(queryUrl).query;
console.log(queryUrl); // name=bigbear&memo=helloworld
console.log(qs.parse(queryUrl));
執行結果:
name=bigbear&memo=helloworld
{ name: 'bigbear', memo: 'helloworld' }
querystring.stringify(obj, [sep], [eq], [options]):把物件序列化成查詢字串,可自訂分隔符(預設 &)與賦值符(預設 =)。
querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// 'foo:bar;baz:qux'
querystring.parse(str, [sep], [eq], [options]):把查詢字串反序列化成物件。options 中的 maxKeys(預設 1000)可限制處理的鍵數量,設為 0 則不限制。
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
// { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
值得注意的一點:同名參數會被收集成陣列,沒有賦值的鍵則對應空字串。
Path 模組提供了一整套處理與轉換檔案路徑的工具函式。要特別留意的是,它幾乎只做字串運算,不會去檔案系統驗證路徑是否真實存在。
var path = require("path");
var queryUrl = "https://localhost:8888/bb?name=bigbear&memo=helloworld";
var root = path.basename(queryUrl);
console.log(root); // bb?name=bigbear&memo=helloworld
basename() 會回傳路徑中最後一段,以「/」作為切分依據。
var ext = path.extname(root); console.log(ext || "Not Ext Name !"); // Not Ext Name !
由於 API 數量眾多,這裡只列出最常見的幾個,其餘建議直接翻閱官方文件。
情境是這樣的:伺服器收到請求後,先用 path 判斷請求的是靜態資源還是頁面,再決定回應哪個檔案。
<!doctype html>
<html>
<head>
<title>Bigbear</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
div {
margin-top: 50px;
width: 100%;
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>
alert("Hello bb !");
var http = require("http");
var fs = require('fs');
var path = require("path");
http.createServer(function (request, response) {
var method = request.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,打開瀏覽器拜訪 https://localhost:8888/ 即可看到效果。
url 負責拆解、querystring 負責參數轉換、path 負責路徑運算。