node.js接收异步任务结果的两种方法----callback和事件广播
作者:互联网
- 事件广播 发送方调用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) }
标签:node,fs,require,eventemitter,js,callback,var,data,events 来源: https://www.cnblogs.com/saintdingspage/p/11737419.html