Search code examples
node.jsrestifyeventemitter

Node.js EventEmitter error


I have an error when trying to inherit EvenEmitter

/* Consumer.js */
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var Consumer = function() {};

Consumer.prototype = {
  // ... functions ...
  findById: function(id) {
    this.emit('done', this);
  }
};

util.inherits(Consumer, EventEmitter);
module.exports = Consumer;

/* index.js */
var consumer = new Consumer();
consumer.on('done', function(result) {
  console.log(result);
}).findById("50ac3d1281abba5454000001");

/* ERROR CODE */
{"code":"InternalError","message":"Object [object Object] has no method 'findById'"}

I've tried almost everything and still dont work


Solution

  • A couple of things. You are overwriting the prototype rather than extending it. Also, move the util.inherits() call before you add the new method:

    var EventEmitter = require('events').EventEmitter;
    var util = require('util');
    
    var Consumer = function Consumer() {}
    
    util.inherits(Consumer, EventEmitter);
    
    Consumer.prototype.findById = function(id) {
        this.emit('done', this);
        console.log('found');
    };
    
    var c = new Consumer();
    c.on('done', function(result) {
      console.log(result);
    });
    
    c.findById("50ac3d1281abba5454000001");