var url = require("url");
var http = require('http');
var fs = require("fs");
var path = require("path");
var PORT = 8000;
var mime = require("./mime").types;
var config = require("./config");
var server = http.createServer(function(request, response) {
if(request.url == ''){
response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
}
var pathname = url.parse(request.url).pathname;
var realPath = path.join("assets", pathname);
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || "text/plain";
response.setHeader("Content-Type", contentType);
fs.stat(realPath, function (err, stat) {
var lastModified = stat.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]) {
response.writeHead(304, "Not Modified");
response.end();
} else {
fs.readFile(realPath, "binary", function(err, file) {
if (err) {
response.writeHead(500, "Internal Server Error", {'Content-Type': 'text/plain'});
response.end(err.toString());
} else {
response.writeHead(200, "Ok");
response.write(file, "binary");
response.end();
}
});
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");