express-1 从Node开始

hello world###

var http = require('http');

http.createServer(function (req, res) {
	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('Hello World');
}).listen(3000);

console.log('Server begin');

事件驱动编程###

Node的核心理念时事件驱动编程,即了解有哪些事件以及如何响应这些事件;前面例子中,HTTP请求就是要处理的事件,http.createServer方法将函数作为一个参数,描述如何响应这个事件

路由###

指向客户端提供它说发出的请求内容的机制;对基于web的客户端/服务端编程而言,就是客户端在URL中指明它想要的内容,具体来说就是路径和查询字符串

修改前面的例子

var http = require('http');

http.createServer(function (req, res) {
	var path = req.url.replace(/?(?:?.*)?$/, '').toLowerCase();
	console.log(path);
	switch(path) {
		case '/':
		  res.writeHead(200, { 'Content-Type': 'text/plain' });
		  res.end('Homepage');
		  break;
		case '/about':
		  res.writeHead(200, { 'Content-Type': 'text/plain' });
		  res.end('About');
		  break;
		default:
		  res.writeHead(404, { 'Content-Type': 'text/plain' }); 
		  res.end('Not Found');
		  break;  
	}

}).listen(3000);

静态资源服务###

静态资源:HTML和图片等这些内容不会变化的资源;用Node提供静态资源只适用于初期的小型项目,对于比较大的项目,你应该会想用Nginx或CDN之类的代理服务器来提供静态资源

使用Apache或IIS,只是创建一个HTML文件,访问它,然后让它自动发送到客户端。使用Node则必须打开文件,读取其中的内容,然后将这些内容发送给浏览器。

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

function serverStaticFile(res, path, contentType, responseCode) {
	var responseCode = responseCode || 200;
	fs.readFile(__dirname +'/' + path, function(err, data) {
		console.log(err);
		if(err) {
			res.writeHead(500, {'Content-Type': 'text/plain'});
			res.end('500 - Internal Error');
		} else {
			res.writeHead(responseCode, {'Content-Type': contentType});
			res.end(data);
		}
	});
}

http.createServer(function (req, res) {
	var path = req.url.replace(/?(?:?.*)?$/, '').toLowerCase();
	switch(path) {
		case '/':
		  serverStaticFile(res, 'public/home.html', 'text/html');
		  break;
		case '/about':
		  serverStaticFile(res, 'public/about.html', 'text/html');
		  break;
		case '/logo.jpg':
		console.log(0);
		  serverStaticFile(res, 'public/logo.jpg', 'image/jpg');  
		  break;
		default:
		  serverStaticFile(res, 'public/404.html', 'text/html', 404);
		  break;  
	}
}).listen(3000);
console.log('Server start');

fs.readFile是读取文件的异步方法。这个函数有同步版本,fs.readFileSync。它调用fs.readFile读取指定文件中的内容,fs.readFile读取完文件后执行回调函数,如果文件不存在,或者读取文件时遇到许可权限方面的问题,会设定err变量,并且会返回一个HTTP 500的状态码表明服务器错误。如果文件读取成功,文件会带着特定的响应码和内容类型发给客户端。

__dirname会被解析为正在执行的脚本所在的目录。

原文地址:https://www.cnblogs.com/jinkspeng/p/4279065.html