var PORT = 8000;
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");
var util = require("util");
var mime = require("./mime").types;
var configExpires = require("./config").Expires;
var configCompress = require("./config").Compress;
var zlib = require('zlib');
var server = http.createServer(function (req, resp) {
var reqURI = url.parse(req.url);
var pathname = reqURI.pathname;
if(pathname == '/favicon.ico') {
return resp.end("/favicon.icon");
}
var realpath = path.join(__dirname + "/assets", pathname);
var ext = path.extname(realpath);
ext = ext ? ext.slice(1) : 'unknown';
if(ext.match(configExpires.fileMatch)){
var expires = new Date();
expires.setTime(expires.getTime() + configExpires.maxAge * 1000);
resp.setHeader('Expires', expires.toUTCString());
resp.setHeader('Cache-Control', 'max-age=' + configExpires.maxAge);
}
var contentType = mime[ext] || 'text/plain';
if(contentType.indexOf('text')>=0){
contentType += "; charset=utf-8";
}
var acceptEncoding = req.headers['accept-encoding'];
console.log(acceptEncoding);
fs.stat(realpath, function cb (err, stat) {
if(err){
resp.writeHead(404, {
'Content-Type': contentType,
});
return resp.end("文件不存在!");
}
var lastModified = stat.mtime.toUTCString();
resp.setHeader('Last-Modified', lastModified);
if(req.headers['if-modified-since'] && lastModified == req.headers['if-modified-since']){
resp.writeHead(304, 'Not Modified');
return resp.end();
}
var raw = fs.createReadStream(realpath);
var matchCompress = ext.match(configCompress.match);
if(matchCompress && acceptEncoding.match(/\bgzip\b/)){
console.log("compress:" + contentType);
resp.writeHead(200, {
'Content-Type': contentType,
'Content-Encoding': 'gzip',
});
return raw.pipe(zlib.createGzip()).pipe(resp);
}
if(matchCompress && acceptEncoding.match(/\deflate\b/)){
resp.writeHead(200, {
'Content-Type': contentType,
'Content-Encoding': 'deflate',
});
return raw.pipe(zlib.createDeflate()).pipe(resp);
}
resp.writeHead(200, {
'Content-Type': contentType,
});
raw.pipe(resp);
});
});
server.listen(PORT);