var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname; //获取路径
var html = route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(html);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
路由router.js
function route(handle, pathname) {
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
return pathname + ' is not defined';
}
}
exports.route = route;
业务处理模块 requestHandlers.js
提供两个函数,返回不同的字符串。
//业务处理模块
function listCategory() {
return "a lot of categorys";
}
function listProduct() {
return "a lot of products";
}
exports.listCategory = listCategory;
exports.listProduct = listProduct;
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/listCategory"] = requestHandlers.listCategory;
handle["/listProduct"] = requestHandlers.listProduct;
server.start(router.route, handle);