- 事件广播 发送方调用emit方法,接收方调用on方法,无论发送方或是接收方,都会工作在一个频道
声明了一个模块,用于读取mime.json中的记录 var fs = require(‘fs‘); var events = require(‘events‘); var eventemitter = new events.EventEmitter(); var getmimetype = function (path,eventemitter,suffix) { fs.readFile(path,function (err,data) { if(err){ console.log(err); return false; } var filedata = JSON.parse(data.toString()); eventemitter.emit(‘wenwa‘,filedata[suffix]); //console.log(filedata[suffix]) }) }; module.exports = getmimetype;
- 接收方
也就是在另一个文件中调用写好的模块,并声明广播的接收方 var eventer = require(‘./readfile_events‘); var fs = require(‘fs‘); var events = require(‘events‘); var eventemitter = new events.EventEmitter(); eventer(‘./mime.json‘,eventemitter,‘.css‘); eventemitter.on(‘wenwa‘,function (data) { console.log(data) });
- 回调函数
//定义模块var fs = require(‘fs‘); var gettype = function (suffix,callback) { fs.readFile(‘./mime.json‘,function (err,data) { if(err){ console.log(err); return false; } var filedata = JSON.parse(data.toString()); //console.log(filedata[suffix]); callback(filedata[suffix]) }) }; module.exports = gettype;
//调用模块var gettype = require(‘./readfilecallback.js‘); var fs = require(‘fs‘); var events = require(‘events‘); var eventemitter = new events.EventEmitter(); gettype(‘.323‘,mycallback); function mycallback(data) { console.log(data) }
原文地址:https://www.cnblogs.com/saintdingspage/p/11737419.html
时间: 2024-10-05 05:09:37