今天说说模块,顺便扯下热更新,(二)中把html,js,css等缓存放在cache的对象中,以达到缓存文件的目的.
但是正常项目一般都是用nginx + express的结构完成静态文件与动态代码的分离(等把express写完,再写写这两个框架的结合),可以参考下这篇,零启动时间
回到模块module,达到封装的目的,(二)中的mime就是一个模块,可以用来参照,module.exports = mime;,外部只能访问到module.exports这个对象,所以我们就给这个对象赋值就好。
这里涉及到js对象,我们就先不用js的原型链prototype的概念,因为涉及到对象的继承,不在这里讨论。
1、创建cache.js文件
var index = 0;
function CacheManager(){
console.log("cacheManager created:"+(++index));
}
//创建对象
var cacheManager = new CacheManager();
//清所有缓存
cacheManager.st_clear_all=function(cache){
console.log(cache);
cache={};
console.log(cache);
return cache;
}
module.exports = cacheManager;// 外部只能访问到module.exports这个对象,所以我们就给这个对象赋值,或者添加属性就好。
2、修改server.js,引入缓存管理模块var cachemanager=require(‘./cachemanager’);,并调用cache = cachemanager.st_clear_all(cache);
var http=require('http');
var fs =require('fs');
var path=require('path');
var mime=require('mime');
var cachemanager=require('./cachemanager');//自定义的模块 缓存管理
//缓存 减少io
var cache={};
//创建服务
var server=http.createServer(function(req,res){
var filepath=false;
switch (req.url){
case '/':
filepath='/public/index.html';
break;
case '/clearcache':
cache = cachemanager.st_clear_all(cache);
//cache={};//刷新缓存 http://localhost:9001/clearcache
break;
default :
filepath=req.url;
break;
}
console.log(filepath);
var abspath='.'+filepath;
serverStatic(res,cache,abspath);
});
//开启服务
server.listen(9001,function(){
console.log('localhost:9001 server is started');
})
function rend404(response){
response.writeHead(404,{"Content-Type":'text/plain'});
response.write('ERROR:404 source not found.');
response.end();
}
//文件数据服务
function rendFile(response,filePath,fileContents){
log('render----'+filePath);
response.writeHead(200,{"Content-Type":mime.lookup(path.basename(filePath))});
response.end(fileContents);
}
//提供静态文件服务
function serverStatic(response,cache,absPath){
if(cache[absPath]){//检查文件是否在缓存中
log('在缓存中--'+absPath);
rendFile(response,absPath,cache[absPath]);
}else{//不在缓存中
fs.exists(absPath,function(exists){//检查文件是否存在
if(exists){//存在
fs.readFile(absPath,function(err,data){//读取文件
if(err){//读取失败
log('读取失败--'+absPath);
rend404(response);
}else{//读取成功
cache[absPath]=data;//添加数据到缓存
rendFile(response,absPath,data);
}
})
}else{//不存在
log('不存在--'+absPath);
rend404(response);
}
});
}
}
function log(msg){
console.log(msg);
}