node.js学习之用路由方法获取简单的图文html页面

来源:互联网 发布:网络博客报警有用吗 编辑:程序博客网 时间:2024/06/05 05:55

程序主程序n8_routehtml.js

var http = require('http');    var url = require('url');var router = require('./models/router');  http.createServer(function(request,response){                    if(request.url!=="/favicon.ico"){    //清除第2此访问    /*获取要访问的页面*/                pathname=url.parse(request.url).pathname;                pathname  =  pathname.replace(/\//,'');//替换掉前面的///console.log(pathname);//由route调用不同的方法                router[pathname](request,response);        }}).listen(3000);    console.log('Server running at http://127.0.0.1:3000/');
./models/router.js:

//导入文件操作对象var optfile = require("../models/optfile.js");//getRecall作为一个公共的函数,访问不同的页面时,由不同的函数调用function getRecall(res,req){res.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'}); function recall(data){res.write(data);res.end('');}return recall;}module.exports={login:function(req,res){//登录页面//res.write("I am login function");recall = getRecall(res,req);optfile.readfile('./views/login.html',recall);},register:function(req,res){//注册页面//res.write("I am register function");recall = getRecall(res,req);optfile.readfile('./views/register.html',recall);},showimg:function(req,res){res.writeHead(200,  {'Content-Type':'image/jpeg'});  optfile.readimg('./image/cbd.jpg',res); }}
./models/optfile.js:

var fs = require('fs');module.exports={readfile:function(path,recall){//异步读取文件fs.readFile(path,function(err,data){if(err){console.log(err);}else{//res.write(data.toString());recall(data);//res.end('');}});console.log("异步方法执行完毕");},readimg:function(path,res){//异步方式读取图片fs.readFile(path,'binary',function(err,data){if(err){console.log(err);return;}else{res.write(data,'binary');res.end('');}});}}
要读取的页面在./views文件夹下

login.html

<!DOCTYPE html><html><head><meta charset="utf-8" /><title>欢迎登陆</title></head><body><h2>welcome to node.js</h2><img src="http://localhost:3000/showimg"/></body></html>

运行结果:





原创粉丝点击