Node.js 路由改造

下面我们利用之前学习的Node.js路由http://blog.csdn.net/cckevincyh/article/details/78305846和读取文件http://blog.csdn.net/cckevincyh/article/details/78307575和读取图片http://blog.csdn.net/cckevincyh/article/details/78311255,通过路由将页面文本内容和图片结合起来显示在页面中

我们先创建一个登录界面的html

<html>
    <head>
    </head>
    <body>
        登录界面
            <img src= "./showImg"/>
    </body>
</html>

然后我们改造我们的router.js

var optfile = require('./fs_read');

function getRecall(req,res){
    function recall(data){
        res.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});
        res.write(data);
        res.end('');    
    }
    return recall;
}


module.exports = {

    login : function(req,res){
        recall = getRecall(req,res);
        optfile.readfile('login.html',recall);
    },

    register : function(req,res){
        recall = getRecall(req,res);
        optfile.readfile('register.html',recall);
    },


    showImg : function(req,res){
        res.writeHead(200,{'Content-Type' : 'image/jpeg'});
        optfile.readImg('./1.png',res);
    }


}

fs_read.js如下:

var fs = require("fs");

module.exports = {

    readfileSync : function(path){//同步读取
        var data = fs.readFileSync(path,'utf-8');
        console.log(data);
        console.log("同步方法执行完毕");
    },

    readfile : function(path,recall){//异步执行
        fs.readFile(path,function(err,data){
            if(err){
                console.log(err);
            }else{
                recall(data);   //回调recall函数,它是闭包函数,它会存储原来的response对象
                console.log(data.toString());
            }
        });
        console.log("异步方法执行完毕");

    },

    readImg : function(path,res){
        fs.readFile(path,'binary',function(err,file){
            if(err){
                console.log(err);
                return ;
            }else{
                res.write(file,'binary');
                res.end();
            }
        });
    }
}

主程序如下:

var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function(request,response){
    if(request.url != '/favicon.ico'){
        var pathname = url.parse(request.url).pathname;
        pathname = pathname.replace(/\//,'');   //替换掉前面的'/'
        console.log("Request for " + pathname + " received.");
        router[pathname](request,response);
    }   
}).listen(8000);

console.log('Server running at http://127.0.0.1:8000');

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值