不好的实现方式
对于我们这样拥有PHP或者Ruby技术背景的开发者来说,最直截了当的实现方式事实上并不是非常靠谱: 看似有效,实则未必如此。
这里我指的“直截了当的实现方式”意思是:让请求处理程序通过onRequest函数直接返回(return())他们要展示给用户的信息。
我们先就这样去实现,然后再来看为什么这不是一种很好的实现方式。
requestHandlers的模块
应用程序需要新的部件,因此加入新的模块 -- 已经无需为此感到新奇了。我们来创建一个叫做requestHandlers的模块,并对于每一个请求处理程序,添加一个占位用函数,随后将这些函数作为模块的方法导出:
requestHandlers的模块,并对于每一个请求处理程序,添加一个有返回值的函数,随后将这些函数作为模块的方法导出:
requestHandlers.js
- function start() {
- console.log("Request handler 'start' was called.");
- return "Hello Start";
- }
- function upload() {
- console.log("Request handler 'upload' was called.");
- return "Hello Upload";
- }
- exports.start = start;
- exports.upload = upload;
router模块
通过检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数,并返回相应是字符串
router.js
- function route(handle, pathname) {
- console.log("About to route a request for " + 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;
server模块
处理请求模块
server.js
- var http = require("http");
- var url = require("url");
- function start(route, handle) {
- function onRequest(request, response) {
- var pathname = url.parse(request.url).pathname;
- console.log("Request for " + pathname + " received.");
- response.writeHead(200, {"Content-Type": "text/plain"});
- //处理不同的输出
- var content = route(handle, pathname)
- response.write(content);
- response.end();
- }
- http.createServer(onRequest).listen(8888);
- console.log("Server has started.");
- }
- exports.start = start;
index模块
启动模块,主模块
index.js
- var server = require("./server");
- var router = require("./router");
- var requestHandlers = require("./requestHandlers");
- //区分大小写的
- var handle = {}
- handle["/"] = requestHandlers.start;
- handle["/start"] = requestHandlers.start;
- handle["/upload"] = requestHandlers.upload;
- server.start(router.route, handle);
运行后效果
如果现在启动应用(node index.js,始终记得这个命令行),随后请求一个URL,我请求的分别是是http://localhost:8888/starT,http://localhost:8888/start,http://localhost:8888/,http://localhost:8888/upload,你将会看到应用输出相应的信息,这表明我们的HTTP服务器已经在使用路由模块了,并会将请求的路径传递给路由,路由再找到对应的处理函数:

好,那么问题在哪里呢?简单的说就是: 当未来有请求处理程序需要进行非阻塞的操作的时候,我们的应用就“挂”了。

