帶著這些知識,我們再來看看我們簡約而不簡單的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_?函數傳遞了一個匿名函數。
用這樣的代碼也可以達到同樣的目的:
~~~
var http = require("http");
function onRequest(request, response) {
? response.writeHead(200, {"Content-Type": "text/plain"});
? response.write("Hello World");
? response.end();
}
http.createServer(onRequest).listen(8888);
~~~
也許現在我們該問這個問題了:我們為什么要用這種方式呢?