node.js learning example 1 (阻塞)


1.index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.begin;
handle["/begin"] = requestHandlers.begin;
handle["/end"] = requestHandlers.end;
server.start(router.route, handle);


2.server.js

var http = require("http");
var url = require("url");
function start(route,handle){
	function onRequest(request,response){
		console.log("-----------begin-------------");
		var pathname = url.parse(request.url).pathname;
		console.log("pathname-----------"+pathname);
		var content = route(handle, pathname);
		response.writeHead(200,{"content-type":"text/plain"});
		console.log(content);
		response.write(content);
		response.end();
		console.log("-----------end-------------");
	}
	http.createServer(onRequest).listen(8889);
	console.log("Server is starting...");
}
exports.start = start;


3.router.js

function route(handle, pathname){
	console.log("Route the request---------"+pathname);
	if(typeof handle[pathname] === 'function'){
		return handle[pathname]();
	}else{
		console.log("no request handler found for" + pathname);
		return "404 Not Found!";
	}
}
exports.route = route;


4.requestHandlers.js

function begin(){
	console.log("handle the 'begin' call!");
	return "begin!";
}
function end(){
	console.log("handle the 'end' call!");
	return "end!";
}
exports.begin = begin;
exports.end = end;

5. run -- node index.js




發佈了33 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章