Node.js 函数
先聊聊JavaScript中,一个函数作为另个函数参数的情况,当然Node.js也能如下方式玩:
// 定义 sayHello 函数
var sayHello = function sayHello(word){
console.log("sayHello : "+word);
}
// 定义 execute 函数
function execute(theFunction,value){
theFunction(value);
}
// sayHello函数 作为参数传递
execute(sayHello,"Hello,Humam!");
运行结果:
sayHello : Hello,Humam!
匿名函数
Node.js也可以把函数当做参数传递,无需 "先定义,后传递",我们可以在函数的括号里直接定义传递函数
见如下代码:
// 定义一个函数,其中一个参数为另一个函数
function execute(theFunction,value){
theFunction(value);
}
// 执行execute函数,在括号中直接定义、传递函数
execute(function(value){
console.log(value);
},"Hello,Human!!");
运行结果:
Hello,Human!!
这就是所谓的匿名函数
So,问题来了,函数传递如何让HTTP服务器工作的?
写法1:
// 引入http模块
var http = require('http');
// 定义 onRequest函数
function onRequest(request,response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("Hello,Human");
response.end();
}
// 函数onRequest传递给createServer
http.createServer(onRequest).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');
----------------------------------------------------------------------
写法2:
// 引入 http 模块
var http = require('http');
// 匿名函数作为参数传入 createServer
http.createServer(function(request,response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("Hello,Human! Hello,NodeJS!!");
response.end();
}).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');