Merujuk kepada contoh pelayan statik pada cnodejs.org, saya menulis contoh pelayan statik nodejs berikut, yang termasuk cache dan mampatan Kodnya adalah seperti berikut:
var ifModifiedSince = "If-Modified-Since".toLowerCase();
response.setHeader("Last-Modified", lastModified);
var tamat tempoh = new Date();
expires.setTime(expires.getTime() config.Expires.maxAge * 1000);
response.setHeader("Tamat tempoh", tamat tempoh.toUTCString());
response.setHeader("Cache-Control", "max-age=" config.Expires.maxAge);
}
jika (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
console.log("从浏览器cache里取")
response.writeHead(304, "Tidak Diubah Suai");
response.end();
} lain {
var raw = fs.createReadStream(realPath);
var acceptEncoding = request.headers['accept-encoding'] || "";
var dipadankan = ext.match(config.Compress.match);
jika (dipadanan && terimaPengekodan.match(/bgzipb/)) {
response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'});
raw.pipe(zlib.createGzip()).pipe(respons);
} lain jika (berpadanan && acceptEncoding.match(/bdeflateb/)) {
response.writeHead(200, "Ok", {'Content-Encoding': 'deflate'});
raw.pipe(zlib.createDeflate()).pipe(respons);
} lain {
response.writeHead(200, "Ok");
raw.pipe(respons);
}
}
}
}
});
}
pathHandle(realPath);
});
server.listen(port);
console.log("Pelayan http dijalankan dalam port:" port);
首先需要在JS文件里创建一个aset的文件夹,里面放入你要浏览的静态文个assets的文件夹,里面放入你要浏览的静态文个从,文从,文从,文从,有从他。
运行方式为:在命令行里切换到上面的JS的文件目录,然后输入 nod JS文件名>浏览器内输入http://localhost:3333/就会看到效果。--补上上面代码里缺少的两个模块
mime.js
"css": "teks/css",
"gif": "imej/gif",
"html": "teks/html",
"ico": "imej/x-icon",
"jpeg": "imej/jpeg",
"jpg": "imej/jpeg",
"js": "teks/javascript",
"json": "application/json",
"pdf": "aplikasi/pdf",
"png": "imej/png",
"svg": "imej/svg xml",
"swf": "application/x-shockwave-flash",
"tiff": "imej/tiff",
"txt": "teks/biasa",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "teks/xml"
};
config.js
eksport.Mampat = {
padankan: /css|js|html/ig
};
eksport. Selamat Datang = {
fail: "index.html"
};