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

程序主程序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>

运行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值