首页 > 代码库 > 一个NodeJS写的基于MVC的服务器

一个NodeJS写的基于MVC的服务器

目前实现了静态文件下载、根据地址导航到控制器相应的控制器方法,但视图模版功能目前还未实现。

 

服务器代码(httpserver.js):

var http = require("http"),     url = require("url"),     path = require("path"),    fs = require("fs"),    getContentType=function(type){        var type=type.indexOf(".")===0 ? type.substr(1) : type,            defType="application/octet-stream",            types={                html:"text/html",                js:"text/javascript",                css:"text/css",                gif:"image/gif",                jpg:"image/jpeg",                png:"image/png",            };        return typeof(types[type])!="undefined" ? types[type] : defType;    };http.createServer(function(req, res) {    var pathname=url.parse(req.url).pathname;    if(pathname=="/"){        pathname+="index.html";    }    pathname=__dirname+pathname;    console.log(req.url);    if(req.url.match(/^\/controller\//) || req.url.match(/^\/data\//)){ //禁止访问目录        res.writeHead(404, {"Content-Type" : "text/html"});    }else if(req.url.match(/^\/\w+\/\w+(\?.*)?$/)){ //控制器输出        var u=url.parse(req.url),            ca=u.pathname.substr(1).split("/"),            c=ca[0],a=ca[1],            cpath=__dirname + "/controller/"+c+".js",            controller;        if(fs.existsSync(cpath)){            res.writeHead(200, {"Content-Type" : getContentType("html")});            controller=require(cpath);            if(typeof(controller[a])!="undefined"){                controller[a](res,u);            }            //delete require.cache[cpath]; //是否清空脚本缓存        }else{            res.writeHead(200, {"Content-Type" : getContentType("html")});            res.end(path+" not exists!");        }    }else if(fs.existsSync(pathname)){//静态文件输出        res.writeHead(200, {"Content-Type" : getContentType(path.extname(pathname))});        fs.readFile(pathname, function(err, data) {            res.end(data);        });    }else{        res.writeHead(404, {                "Content-Type" : getContentType("html")        });        res.end("<h1>404 Not Found</h1>");    }}).listen(8080, "127.0.0.1");console.log("Server running at http://127.0.0.1:8080/");

 

控制器代码(controller/project.js):

var tm=1,    mysql=require("mysql"),    conn = mysql.createConnection({            host: ‘127.0.0.1‘,            user: ‘root‘,            password: ‘123456‘,            database:‘dbname‘,            port: 3306        });conn.connect();var project={    show:function(res,url){        var paras={},tb="user";        console.log(url.query);        if(typeof(url.query)=="string"){            var ps=url.query.split("&"),pss;            for(var k in ps){                pss=ps[k].split("=");                paras[pss[0]]=pss[1];            }        }        res.write((tm++)+"<br/>");        conn.query(            ‘SELECT * from prefx_‘+(typeof(paras.tb)!="undefined" ? paras.tb : tb )+‘ limit 0,3‘,             function(err, results, fields){                var field="",str="",fds=[];                if (results) {                    for(var k in fields){                        fds.push(fields[k][‘name‘]);                    }                    for ( var i = 0; i < results.length; i++) {                        str="";                        for(var k in fds){                            str+=results[i][fds[k]]+"\t";                        }                        res.write(str+"<br/>");                    }                }                res.end("<br/>"+(new Date()).getTime());            }        );    }}module.exports=project;

 

网站目录结构如下:

技术分享

例如访问:http://127.0.0.1:8080/project/show,则访问project控制器中show方法

一个NodeJS写的基于MVC的服务器