实用events做个小例子:
var mysql = require("mysql"); var Event = require("events").EventEmitter; var user = "lubingjie"; var pass = "123456"; var db = mysql.createConnection({host:"localhost",user:"root",password:"",database:"test"});//链接数据库 var ev = new Event();//实例化events ev.on("error",function(err){//添加监听err的事件 统一的错误处理函数 console.log("数据库出错了!"); }); function query(sql,fn){//执行函数 db.query(sql,function(err,data){ if(err) ev.emit("err",err);//执行监听的事件 else{ fn(data); } }); } query("select * from user where username=‘"+user+"‘ and pass=‘"+pass+"‘",function(data){ if(data.length==0){ query("insert into user values(‘"+user+"‘,‘"+pass+"‘)",function(data){ console.log("完成!"); }); }else{ console.log("用户名已经存在!"); } });
时间: 2024-10-12 12:51:51