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);
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;
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;
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