Node.js中函数的使用与Javascript类似,一个函数可以作为另一个函数的参数。我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。
function say(word) { console.log(word); } function execute(someFunction, value) { someFunction(value); } execute(say, "Hello");
匿名函数
function execute(someFunction, value) { someFunction(value); } execute(function(word){ console.log(word) }, "Hello");
函数传递是如何让HTTP服务器工作的
var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
现在它看上去应该清晰了很多:我们向 createServer 函数传递了一个匿名函数。
路由
我们要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据来执行相应的代码。因此,我们需要查看HTTP请求,从中提取出请求的URL以及GET/POST参数。
我们的应用现在可以通过请求的URL路径来区别不同请求了--这使我们得以使用路由来将请求以URL路径为基准映射到处理程序上。
在我们所要构建的应用中,这意味着来自/start和/upload的请求可以使用不同的代码来处理。稍后我们将看到这些内容是如何整合到一起的。
现在我们可以来编写路由了,建立一个名为 router.js 的文件,添加以下内容:
function route(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
扩展服务器的start()函数,以便将路由函数作为参数传递过去,server.js 文件代码如下
var http = require("http"); var url = require("url"); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); route(pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8899); console.log("Server has started."); } exports.start = start;
同时,我们会相应扩展index.js,使得路由函数可以被注入到服务器中(这里把route函数作为模块全部传入start中,在start中就可以调用该函数):
var server = require("./server"); var router = require("./router"); server.start(router.route);
执行结果:运行index.js得到
请求http://127.0.0.1:8899/后,你将会看到应用输出相应的信息,这表明我们的HTTP服务器已经在使用路由模块了,并会将请求的路径传递给路由,输出已经去掉了比较烦人的/favicon.ico请求相关的部分。
会将请求的路径传递给路由,比如:先后访问
http://127.0.0.1:8899/ab和http://127.0.0.1:8899/abcdefg得到如下结果