在module.exports函数中生成事件

我试图做一个模块,甚至可以从索引文件中调用(在require之后)。 我的代码包括var events = require("events"); 而且我只写了棘手的部分。

index.js:

 var reqw = require('./module.js'); reqw.on('data', function(d) { console.log(d); }); 

module.js:

 module.exports = { listaccts: function() { events.EventEmitter.call(this); } } util.inherits(exports.listaccts, events.EventEmitter); exports.listaccts.prototype.listme = function() { thisList = this; var req = https.request(requestOptions, function(res) { res.on('data', function(chuck) { store = chuck; }); res.on('end', function(d) { thisList.emit("data", store.toString()); }); }); } 

search了整个我们,但还没有find正确的答案..

稍微修改你的代码:

module.js

 function listaccts(){ } util.inherits(listaccts, EventEmitter); listaccts.prototype.listMe = function(){ var self = this; var store = []; console.log('here'); var req = https.request(requestOptions, function(res) { res.on('data', function(chuck) { console.log('data'); store.push(chuck); }); res.on('end', function() { console.log('end'); self.emit("data", store); }); }); req.end(); }; module.exports = listaccts; 

index.js

 var reqw = require('./module'); var obj = new reqw(); obj.listMe(); obj.on('data', function(err, data) { console.log(err); }); 

req.end是重要的,我忘了包括,并得到一个永无止境的循环。

创build实例来绑定this ,所以不需要EventEmitter.call 。 也许你想要listMe函数到你的构造函数中。

希望这个帮助。