JavaJedi
JavaJedi

Reputation: 221

can't instantiate instance of exported custom module Nodejs, that extends EventEmitter

community. I can't instantiate instance of exported custom module Nodejs.

I have 2 files: one custom test module "resource.js" and "ext-emitter.js"

in resource.js create class of Resource and extend it from EventEmitter class.

    // resource.js
    var util = require("util");
    var eventEmitterInstance = require("events").EventEmitter;


function Resource(m){
    this.maxEvents = m;
    var self = this;

    process.nextTick(function() {
       var count = 0;
       self.emit('start');
       var t = setInterval(function(){
          self.emit('data', ++count);
          if (count === m) {
              self.emit('end', count);
              clearInterval(t);
          }

       }, 10);
    });

}

util.inherits(Resource, eventEmitterInstance);
module.exports = Resource();

Then I import the module above in the next file ext-emitter.js I try to instantiate extended custom module Resource() (which in its turn extends EventEmitter class), but I got an error: " 'Resource' is not defined"

Please help me find the place where I went wrong.

var r = require("./resource");

var r = new Resource(7);

r.on('start', function(){
    console.log("I've started the resource getting process!!!");
});

r.on('data', function(d) {
    console.log("I received this data --> " + d );
});

r.on('end', function(finalCountOfRes){
   console.log("I have finished resource getting. The num of res gotten: " + finalCountOfRes); 
});

Upvotes: 1

Views: 404

Answers (1)

musichen
musichen

Reputation: 116

I think the place where you went wrong was the first line in file "ext-emitter.js" Just be more careful, you could've spotted the mistake yourself: Here you require your custom module "resource.js" and placing it to a variable "r", then you're instantiating new instance of imported module with the same variable "r" and calling new on unknown/undefined within ext-emitter.js Resource() object.

var r = require("./resource");
var r = new Resource(7);

Just keep your eye on var names. Change the first line on:

var Resource = require("./resource");

And it will work just fine.

Upvotes: 1

Related Questions