Skip to content

Instantly share code, notes, and snippets.

@neekey
Created April 14, 2012 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neekey/2382491 to your computer and use it in GitHub Desktop.
Save neekey/2382491 to your computer and use it in GitHub Desktop.
browser cache test
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var transferFile = function (request, response) {
var uri = url.parse(request.url).pathname;
var filepath = path.join(process.cwd(), uri);
path.exists(filepath, function (exists) {
if (!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
} else {
fs.readFile(filepath, "binary", function (error, data) {
if (error) {
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write(error + "\n");
} else {
console.log( 'request: ' + uri, Date.now() );
if( request.headers[ 'if-modified-since' ] ){
console.log( 304 );
response.writeHead( 304 );
}
else {
// 设置max-age为10s,在10s内 只要不进行强制刷新,那么浏览器都将直接使用本地缓存
// 过了10s,对与该资源的请求将重新向服务器获取
response.writeHead(200, {
"Cache-Control": "max-age=10",
"Last-Modified": (new Date).toString()
});
response.write(data, "binary");
}
}
response.end();
});
}
});
}
http.createServer(function(request, response) {
transferFile(request, response);
}).listen(8124, "127.0.0.1");
@neekey
Copy link
Author

neekey commented Apr 14, 2012

在同目录下创建index.html,并虽然写一个简单的index.css文件,在index.html中引入index.css文件,测试浏览器的缓存机制

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment