events模块

 1 /**
 2  * Created by Administrator on 2016/8/3.
 3  */
 4 var http = require("http");
 5 //Node 导入文件系统模块
 6 var fs = require("fs");
 7 //引入events模块
 8 var events = require("events");
 9 //创建eventEmitter对象
10 var eventEmitter = new events.EventEmitter(); //注意大小写
11 //绑定事件以及事件的处理程序
12 eventEmitter.on("oneEvent",function(){
13     //异步读取文件内容的函数: readFile()
14     fs.readFile("index.txt", "utf-8", function(err, data){
15         if(err){
16             console.log(err);
17         }else{
18             console.log(data);
19         }
20     });
21     console.log("end异步");
22 });
23 //触发事件
24 eventEmitter.emit("oneEvent");
25 function start(req, res){
26     res.writeHead(200, {"Content-Type": "text/plain"});
27     res.write("异步读取文件和同步读取文件的对比!");
28     res.end("over");
29 }
30 //创建一个http服务器,并监听端口号为3001,host为127.1.1.1
31 var server = http.createServer(start).listen("3002","127.1.1.1",function(){
32     var port = server.address().port;
33     var host = server.address().address;
34     console.log("应用实例,访问地址为 http://%s:%s", host, port);
35 });
//引入events模块
var events = require("events");
//创建eventEmitter对象
var eventEmitter = new events.EventEmitter(); //注意大小写

//绑定事件以及事件的处理程序
eventEmitter.on("eventName",function(){
console.log("事件处理代码。");
});
//触发事件
eventEmitter.emit("eventName");
posted @ 2016-08-03 14:27  钟离野  阅读(237)  评论(0编辑  收藏  举报