原生node.js服務器搭建

//app.js文件部分:
"use strict";
//console.log("hello word");
const http=require("http");
const  fs=require("fs");
const myFirst=require("./routes/resource");
const server=http.createServer(function (request,respones) {
       console.log("有請求");
     // console.log(url);
       let url=request.url;
       let urlAarry=url.split(".");
        if(urlAarry[1]=="html"){
              myFirst.sendHtml(request,respones);
        } else if(urlAarry[1]=="css"){
              myFirst.sendCss(request,respones);
        } else if(urlAarry[1]=="js"){
              myFirst.sendJs(request,respones);
        }else if(urlAarry[1]=="jpg"||urlAarry[1]=="png"|| urlAarry[1]=="icon"){
              myFirst.sendImag(request,respones);

        }


        // respones.writeHead(200,{"content-type":"text/html;charset=utf-8"});
        // respones.write("<h1 style='color: blueviolet'>我是中國人,我為中國感到驕傲</h1>");
        // respones.end();
});
console.log("啟動服務器");
server.listen(8888);
//resource.js文件部分
"use strict"
const  fs=require("fs");
exports.sendHtml=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/html;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendCss=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/css;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendJs=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,"utf-8",function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/javascript;utf-8"});
            respones.write(data);
            respones.end();
        }
    });
};
exports.sendImag=function (request,respones) {
    let url=request.url;
    fs.readFile("public"+url,function (err,data) {
        if(err==0||err==undefined){
            respones.writeHead(200,{"content-type":"text/jpg"});
            respones.write(data);
            respones.end();
        }
    });
};

 

發佈留言