我正在尝试制作一个带有偶数的模块,我可以从索引文件中调用它(在需要之后)。
我的代码包括 var events = require("events");
并且我在这里只写了棘手的部分。
index.js:
var reqw = require('./module.js');
reqw.on('data', function(d) {
console.log(d);
});
模块.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());
});
});
}
搜索了整个我们,但尚未找到正确的答案..
最佳答案
稍微修改你的代码:
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
很重要,我忘记包含并得到一个永无休止的循环。
已创建用于绑定(bind)this
的实例,因此不需要EventEmitter.call
。
也许您希望将 listMe
函数添加到您的构造函数中。
希望这有帮助。
关于node.js - 在 module.exports 函数中创建事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526315/