笔记
var http=require("http");//引入http模块
var fs=require("fs");//引入文件读写模块
var url=require("url");//引入url处理模块
var server=new http.Server();//实例化一个服务器对象
//监听请求事件
server.on("request",(req,res)=>{
var pathname=url.parse(req.url).pathname;//请求路径
switch(pathname){//路径分析。根据不同的路径返回不同的资源
case ""||"/":
}
});
作业:完善上的代码,实现一个静态资源服务器。
作用
完善课上的代码实现一个静态资源服务器。
创建三个文件:程序入口文件app.js、资源映射文件mime.js、配置文件config.js
程序入口文件app.js
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
var zlib = require("zlib");//压缩模块
var mime = require("./mime").types;
var config = require("./config");
var server = new http.Server();
server.on("request", function (request, response) {//监听请求事件
var pathname = url.parse(request.url).pathname;
switch(pathname){//路由控制;
case "/"||"index":
pathname="/index.html";
break;
}
var realPath = path.join("assets", path.normalize(pathname));
var ext = path.extname(realPath);//解析文件的后缀名;
if(ext){//不处理没有后缀名的realPath,这一点交给路由控制;
fs.stat(realPath, function (err, stat) {//读取文件属性
if (err) {//如果没找到文件返回404
response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});
response.write("NOT FOUND on this server");
response.end();
} else {
ext = ext.slice(1);
var contentType = mime[ext] || "text/plain";
response.setHeader('Content-Type', contentType);
var lastModified = stat.mtime.toUTCString();//文件的最后修改时间
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["if-modified-since"] && lastModified == request.headers["if-modified-since"]) {//判断文件是否修改过
response.writeHead(304, "Not Modified");
response.end();
} else {如果修改过或者第一次传输则返回文件
var raw = fs.createReadStream(realPath);
var ae = request.headers["accept-encoding"] || "";//获取浏览器支持的压缩格式
var matched = ext.match(config.Compress.match);
if (matched && ae.match(/\bgzip\b/)) {
response.writeHead(200, "ok", {"Content-Encoding": "gzip"});
raw.pipe(zlib.createGzip()).pipe(response);
} else if (matched && ae.match(/\bdeflate\b/)) {
response.writeHead(200, "ok", {"Content-Encoding": "deflate"});
raw.pipe(zlib.createDeflate()).pipe(response);
} else {//如果不支持压缩,则直接传输
response.writeHead(200, "ok");
raw.pipe(response);
}
}
}
});
}else{//如果没有后缀名,则直接断开连接
response.end();
}
});
server.listen(3000);
资源映射文件mime.js
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
配置文件config.js
exports.Expires = {//缓存
fileMatch: /^(gif|png|jpg|js|css)$/ig,//需要缓存的文件类型
maxAge: 60*60*24*365//到期时间
};
exports.Compress={//需要压缩传输的文件类型
match:/css|js|html/ig
};