node+express读书笔记1

Node所提供的范式和传统的Web服务器不同,你写的程序就是Web服务器。Node只是给你提供了一个构建Web服务器的框架。

Node的核心理念是事件驱动编程。很多人接触事件驱动编程是从用户界面开始的,用户点击了什么,然后你处理这个“点击事件”。在服务器上响应事件这种概念性的跳跃可能会比较难,但也是一样的。比如:http.createServer,其事件就是隐藏的,HTTP请求就是要处理的函数。

用Node提供静态资源只适用于初期的小型项目,对于比较大的项目,你肯能会想用NginX或者CDN之类的代理服务器来提供静态资源。

如果你用过Apache或者IIS,可能会习惯创建一个文件然后访问它,然后让他自动返回到客户端。Node不是这样,我们必须打开一个文件夹,读取其内容,然后将这些内容发送给浏览器。

fs.readFile读取完文件后执行回调函数,如果文件不存在,或者文件存在读写方面的权限,会设定err变量,并返回一个http 500的状态吗来表明服务器错误。如果文件读取成功,文件会带着特定的响应码和内容返回给客户端。


var http = require('http'),
	fs = require('fs');


function serveStaticFile(res,path,contentType,reponseCode){
	if(!reponseCode){
		reponseCode = 200;
		fs.readFile(__dirname+path,function(err,data){
			if(err){
				res.writeHead(500,{'Content-Type':'text/plain'});
				res.end('500-Internal Error');
			}else{
				res.writeHead(reponseCode,{'Content-Type':'contentType'});
				res.end(data);
			}
		})
	}
}

http.createServer(function(req,res){
	var path = req.url.replace(/\/?(?:\?.*)?$/,'').toLowerCase();
	switch(path){
		case '':
			serveStaticFile(res,'/public/index.html','text/html');
		case '/about':
			serveStaticFile(res,'/public/about.html','text/html');
		case '/img/logo.png':
			serveStaticFile(res,'/public/img/logo.png');
	}
}).listen(3000);

console.log("server started on port:3000");

同样的如果用express的话,代码就该是这样的。

var express = require('express');
var app = express();

//设置端口
app.set('port',process.env.PORT || 3000);


//设置路由
app.get('/',function(req,res){
	res.type('text/plain');
	res.send('index travel');
})

app.get('/about',function(req,res){
	res.type('text/plain');
	res.send('about travel');
})

//定制404页面
app.use(function(req,res){
	res.type('text/plain');
	res.status(404);
	res.send('404 Not-Found');
})

//定制500页面
app.use(function(req,res){
	res.type('text/plain');
	res.status(500);
	res.send('500-Server Error');
})


//监听端口
app.listen(app.get('port'),function(){
	console.log("Express started on http://localhost:"+app.get('port'));
})


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值