回调函数与事件
一、函数
1.异步式readFile
var fs = require('fs');
fs.readFile("file.txt","UTF-8",function(err,data){
if(err){
console.log(err);
}
else{
console.log(data);
}
});
console.log("end");
2.同步式readFileSync
var fs = require('fs');
var data = fs.readFileSync("file.txt","UTF-8");
console.log(data);
console.log("end");
二、事件
1.声明事件对象
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
2.注册事件
event.on("some_event",function(number1,number2){
console.log("这是一个自定义事件");
console.log("number1 = " + number1);
console.log("number2 =" + number2);
});
3.触发事件
setTimeout(function(){
event.emit("some_event",10000,500);//number1=10000,number2=500
})
网友评论