fgfjhgrjr erjhm
fgfjhgrjr erjhm

Reputation: 335

nodejs calling to function from inside an object in module

I have the following module:

var util = require('util');
var events = require('events');
exports.IncomingMessage=IncomingMessage;

var IncomingMessage = function (){
    events.EventEmitter.call(this);
    this.headers={};
    this.httpVersion='';
    this.method='';
    this.socket='';
    this.ready=function(){
        console.log('should emit ready');
        //this.emit('ready');
    }

}

In my code, I'm doing:

var req=require('./newIncomingMessage');

and then when I'm calling:

req.ready();

I'm getting an Error:

TypeError : Object #<Object> has no method 'ready'

Why is that? What am I missing?

Upvotes: 0

Views: 2754

Answers (3)

fgfjhgrjr erjhm
fgfjhgrjr erjhm

Reputation: 335

Well, I couldn't understand from the answers above why the approach didn't work. But that's what I used finally:

module.exports = IncomingMessage;

function IncomingMessage() {
    this.headers={};
        this.httpVersion='';
        this.method='';
        this.socket='';
    }
IncomingMessage.prototype.ready=function(){
    console.log('Inside ready function');
}

Upvotes: 0

albertshaw
albertshaw

Reputation: 96

Just didn't recognize IncomingMessage is used before definition.

var util = require('util');
var events = require('events');
exports.IncomingMessage = new function(){
  events.EventEmitter.call(this);
  this.headers={};
  this.httpVersion='';
  this.method='';
  this.socket='';
  this.ready=function(){
    console.log('should emit ready');
    //this.emit('ready');
  };
};

And before using it

var iMsg=require('./newIncomingMessage').IncomingMessage;

And then you can use it:

iMsg.ready();

A brief explanation about it is:

You can treat new function(){} as {}, but more than {}, because you can do more things in this enclosing scope.

In this example, simply typo

typeof iMsg

your will get an

'object'.

Upvotes: 0

You're missing the module.exports = ... to say what should come out when you require it. If you want it to export an object that has a .ready function, you still need

....
module.exports = { ready: function() { ... } };

that said, I don't see any code in your module that looks like a ready function, so a better question is "what are you trying to do with this code".

On a relatively important note: req is a var name generally reserved for http request objects (either in plain nodejs or connect/express) so you're going to confuse a lot of other Node devs by using that as your variable name.

Upvotes: 1

Related Questions