zoukankan      html  css  js  c++  java
  • 一个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]]+"	";
                            }
                            res.write(str+"<br/>");
                        }
                    }
                    res.end("<br/>"+(new Date()).getTime());
                }
            );
        }
    }
    
    module.exports=project;

    网站目录结构如下:

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

  • 相关阅读:
    You are not late! You are not early!
    在同一个服务器(同一个IP)为不同域名绑定的免费SSL证书
    Vue.js Is Good, but Is It Better Than Angular or React?
    It was not possible to find any compatible framework version
    VS增加插件 Supercharger破解教程
    Git使用ssh key
    Disconnected: No supported authentication methods available (server sent: publickey)
    VS 2013打开.edmx文件时报类型转换异常
    asp.net MVC4 框架揭秘 读书笔记系列3
    asp.net MVC4 框架揭秘 读书笔记系列2
  • 原文地址:https://www.cnblogs.com/springwind2006/p/5872628.html
Copyright © 2011-2022 走看看