Nodejs 入门 12-28

 

/**
 * Created by Administrator on 2016/12/28.
 */
//使用ES6的语法,必须使用严格模式
    "use strict";//r若使用let的局部变量的时候一定要使用严格模式
//引入http模块 http通信
//var 定义全局变量 let定义局部变量 const定义常量
const http=require("http");
const fs=require("fs");
const server=http.createServer(function(request,response){
    let url=request.url;
    console.log(url);
    let urlArray=url.split(".");
    if(urlArray[1]=="html"){
        fs.readFile("public"+url,"utf-8",function(err,data){
            console.log(err);
            console.log(data);
            if(err==null||err==undefined){
                response.writeHead(200,{"content-type":"text/html;charset=utf-8"});
                response.write(data);
                response.end();
            }
        })
    }else if(urlArray[1]=="css"){
        fs.readFile("public"+url,"utf-8",function(err,data){
           if(err==null||err==undefined){
                response.writeHead(200,{"content-type":"text/css;charset=utf-8"});
                response.write(data);
                response.end();
           }
        })
    }else if (urlArray[urlArray.length-1]=="js"){
        fs.readFile("public"+url,"utf-8",function(err,data){
            if(err==null||err==undefined){
                response.writeHead(200,{"content-type":"text/javascript;charset=utf-8"});
                response.write(data);
                response.end();
            }
        })
    }else if(urlArray[1]=="woff"){
        fs.readFile("public"+url,function(err,data){
            if(err==null||err==undefined){
                response.writeHead(200,{"content-type":"application/woff"});
                response.write(data);
                response.end();
            }
        })
    }else if(urlArray[1]=="svg"||urlArray[1]=="jpg"||urlArray[1]=="png"){
        fs.readFile("public"+url,function(err,data){
            if(err==null||err==undefined){
                response.writeHead(200,{"content-type":"image/"+urlArray[1]});
                response.write(data);
                response.end();
            }
        })

    }



    //response.writeHead(200,{"content-type":"text/html;charset=utf-8"});
    //response.write("猪你来了!");
    //response.end();
    //console.log("请求来了!");
    //console.log(request.url);
});
console.log("服务器启用了!");
server.listen(5252);

  

posted @ 2016-12-28 20:05  potato~e-e  阅读(235)  评论(0编辑  收藏  举报