版权声明:版权有就有吧。 https://blog.csdn.net/m0_38044453/article/details/83658509
// 取得http请求
var http = require('http');
// 获取url
var url = require('url');
// 获取路由js
var router = require('./router');
// 创建端口为8000的服务
http.createServer(function(request,response){
if(request.url!=='/favicon.ico'){// 过滤第二次重复请求
// 过滤url中的地址,例如localhost:8000/login,取得其中的login
var pathname = url.parse(request.url).pathname;
pathname=pathname.replace(/\//,'');
// 调用router.js 中的 pathname方法
router[pathname](request,response);
console.log('主程序执行完毕!');
}
}).listen(8000);
console.log('Server running is port 8000! ');
// 获取 readhtml.js
var readhtml = require('./readhtml');
// 封装一个回调函数
function getRecall(req,res){
res.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
function recall(data){
res.write(data);
res.end(''); // 不写没有http结尾
}
return recall;
}
module.exports = {
login:function(req,res){
recall = getRecall(req,res);
// 调用 readhtml.js中的indexhtml方法
readhtml.indexhtml('./view/index.html',recall);
},
showImg:function(req,res){
res.writeHead(200,{'Contet-Type':'image/jpeg'});
// 调用 readhtml.js中的showimg方法
readhtml.showimg('./img/1.jpg',res);
}
}
var fs = require('fs');
module.exports = {
// 读取图片
showimg:function(path,res){
fs.readFile(path,'binary',function(err,filedata){
if(err){
console.log(err);
return;
}else{
res.write(filedata,'binary');
res.end
}
});
},
// 读取html页面
indexhtml:function(path,recall){
fs.readFile(path,function(err,data){
if(err){
console.log(err);
}else{
recall(data);
}
});
}
}