events模块

时间:2022-08-17 06:00:23
 /**
* Created by Administrator on 2016/8/3.
*/
var http = require("http");
//Node 导入文件系统模块
var fs = require("fs");
//引入events模块
var events = require("events");
//创建eventEmitter对象
var eventEmitter = new events.EventEmitter(); //注意大小写
//绑定事件以及事件的处理程序
eventEmitter.on("oneEvent",function(){
//异步读取文件内容的函数: readFile()
fs.readFile("index.txt", "utf-8", function(err, data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
console.log("end异步");
});
//触发事件
eventEmitter.emit("oneEvent");
function start(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("异步读取文件和同步读取文件的对比!");
res.end("over");
}
//创建一个http服务器,并监听端口号为3001,host为127.1.1.1
var server = http.createServer(start).listen("3002","127.1.1.1",function(){
var port = server.address().port;
var host = server.address().address;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});
//引入events模块
var events = require("events");
//创建eventEmitter对象
var eventEmitter = new events.EventEmitter(); //注意大小写
//绑定事件以及事件的处理程序
eventEmitter.on("eventName",function(){
console.log("事件处理代码。");
});
//触发事件
eventEmitter.emit("eventName");