/**
* Created by linyunfu on 2017/4/13.
*/
var http=require('http'),
url=require('url'),
fs=require('fs');
var server1=http.createServer(function(req,res){
//解析客户端请求地址中文件目录名称以及数据内容
var urlObj=url.parse(req.url,true),
pathname=urlObj["pathname"],
query=urlObj["query"],
reg=/\.(HTML|JS|CSS|JSON|TXT|ICO|JPG|PNG|GIF|BMP)/i;
if(reg.test(pathname)){
var suffix=reg.exec(pathname[1].toUpperCase());
// 根据后缀名,获取到当前文件的类型
var suffixMIME='text/plain';
switch(suffix){
case "HTML":
suffixMIME="text/html";
break;
case "CSS":
suffixMIME="text/css";
break;
case "JS":
suffixMIME="text/javascript";
break;
case "JSON":
suffixMIME="application/json";
break;
case "ICO":
suffixMIME="application/octet-stream";
break;
}
//都是字符串格式的
try{
var confile=fs.readFileSync("."+pathname,"utf-8");
//重写响应头信息:告诉客户端浏览器,我返回的内容的格式
res.writeHead(200,{'content-type':suffixMIME+'charset=utf-8;'});
res.end(confile);
}
catch (e){
res.writeHead(404,{'content-type':'text/plain;charset=utf-8;'});
res.end('request loser')
}
}
//如果客户端请求的资源文件不存在(防止服务终止)
try{
var con=fs.readFileSync("."+pathname,'utf-8');
res.end(con);
}catch (e){
res.end("request file is not find");
}
});
server1.listen(1234,function(){
console.log("1234");
});
nodejs
最新推荐文章于 2024-07-31 15:22:58 发布