本文參考 cnodejs.org 社群分享的靜態伺服器範例,實際演練一個功能完整的 Node.js 靜態檔案伺服器。這個版本特別加入了瀏覽器快取(Cache)與 Gzip/Deflate 壓縮機制,能有效降低頻寬消耗並加快頁面載入速度。以下先貼出主程式碼:
var port = 3333;
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
var mime = require("./mime").types;
var config = require("./config");
var zlib = require("zlib");
// 建立 HTTP 伺服器
var server = http.createServer(function (request, response) {
var obj = url.parse(request.url);
response.setHeader("Server", "Node/V8");
console.log(obj);
var pathname = obj.pathname;
if (pathname.slice(-1) === "/") {
pathname = pathname + config.Welcome.file; // 預設取 index.html
}
var realPath = path.join("assets", path.normalize(pathname.replace(/\.\./g, "")));
console.log(realPath);
var pathHandle = function (realPath) {
fs.stat(realPath, function (err, stats) {
if (err) {
response.writeHead(404, "not found", { 'Content-Type': 'text/plain' });
response.write("the request " + realPath + " is not found");
response.end();
} else {
if (stats.isDirectory()) {
} else {
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || "text/plain";
response.setHeader("Content-Type", contentType);
var lastModified = stats.mtime.toUTCString();
var ifModifiedSince = "If-Modified-Since".toLowerCase();
response.setHeader("Last-Modified", lastModified);
if (ext.match(config.Expires.fileMatch)) {
var expires = new Date();
expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
response.setHeader("Expires", expires.toUTCString());
response.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);
}
if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
console.log("從瀏覽器 cache 裡取");
response.writeHead(304, "Not Modified");
response.end();
} else {
var raw = fs.createReadStream(realPath);
var acceptEncoding = request.headers['accept-encoding'] || "";
var matched = ext.match(config.Compress.match);
if (matched && acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, "Ok", { 'Content-Encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else if (matched && acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, "Ok", { 'Content-Encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else {
response.writeHead(200, "Ok");
raw.pipe(response);
}
}
}
}
});
};
pathHandle(realPath);
});
server.listen(port);
console.log("http server run in port:" + port);
使用之前,請先在 JS 檔案同目錄下建立一個名為 assets 的資料夾,把你想提供的靜態資源(例如 index.html、demo.js 等)放進去。
執行方式很簡單:開啟命令列,切換到該 JS 檔案所在目錄,輸入 node 檔案名稱 即可啟動。接著在瀏覽器輸入 https://localhost:3333/,就能看到成果了。
負責將檔案副檔名對應到正確的 Content-Type:
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
集中管理快取、壓縮與預設首頁的設定:
exports.Expires = {
fileMatch: /^(gif|png|jpg|js|css)$/ig,
maxAge: 60 * 60 * 24 * 365
};
exports.Compress = {
match: /css|js|html/ig
};
exports.Welcome = {
file: "index.html"
};
透過這三個檔案的搭配,你便擁有一個具備 304 快取驗證、依副檔名自動判斷壓縮格式的輕量級靜態伺服器,非常適合本地開發與靜態網站託管。