关闭

原生node.js服务器搭建

90人阅读 评论(0) 收藏 举报
分类:


//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();
        }
    });
};




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10575次
    • 积分:409
    • 等级:
    • 排名:千里之外
    • 原创:28篇
    • 转载:22篇
    • 译文:0篇
    • 评论:0条