Skip to content

Instantly share code, notes, and snippets.

@xuyanbo03
Created January 24, 2018 03:05
Show Gist options
  • Save xuyanbo03/f2ce011d71a126e68f2e1d60ecf9cea2 to your computer and use it in GitHub Desktop.
Save xuyanbo03/f2ce011d71a126e68f2e1d60ecf9cea2 to your computer and use it in GitHub Desktop.
node cache practise
//app.js
var PORT=3000;
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 server=http.createServer(function(request,response){
var pathname=url.parse(request.url).pathname;
var realPath='publice'+pathname;
var ext=path.extname(realPath);
ext=ext?ext.slice(1):'unknown';
var contentType=mime[ext]||'text/plain';
//Cache-Control
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);
}
//Last-Modified
fs.stat(realPath,function(err,stat){
var lastModified=stat.mtime.toUTCString();
response.setHeader('Last-Modified',lastModified);
if(request.headers['if-modified-since'] && lastModified==request.headers['if-modified-since']){
response.writeHead(304,'Not Modified');
response.end();
}else{
fs.exists(realPath,function(exists){
if(!exists){
response.writeHead(404,{
'Content-Type':'text/plain'
});
response.write('This URL'+pathname+'not found');
response.end();
}else{
fs.readFile(realPath,'binary',function(err,file){
if(err){
response.writeHead(500,{
'Content-Type':'text/plain'
});
response.end();
}else{
response.writeHead(200,{
'Content-Type':contentType
});
response.write(file,'binary');
response.end();
}
})
}
})
}
})
});
server.listen(PORT);
console.log('port:'+PORT);
//config.js
exports.Expires={
fileMatch:/^(png|gif|jpg|js|css)$/ig,
maxAge:60*60*24*365
}
//mime.js
exports.types={
'jpg':'image/jpeg',
'json':'application/json'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment