18

I have a module I created for a node.js app. The app also uses socket.io and I want to pass the socket.io object into the auction object when I create it.

This works when I do it outside of Node, but inside, I get the error 'object is not a function' - my guess is it has to do with the module.exports, but I'm sure what it would be.

Any suggestions would be awesome - thank you!

auction.js

var Auction = function(socket) {
    this.data      = [];
    this.timer     = null;
    this.socket    = socket;
}

Auction.prototype = {

    add: function(auction) {
        this.data.push(auction);
    }
}


module.exports.Auction = Auction;

server.js:

var  Auction          = require('./lib/auction');

var auctions = new Auction(socket);

Error: TypeError: object is not a function at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)

1 Answer 1

38

You are exporting an object with 1 property Auction

When you required the module, you imported an object which looks like

{
  Auction: function(){...}// Auction function
}

So either export just the function:

module.exports = Auction;

or reference the property when you require the module:

var  Auction = require('./lib/auction').Auction;

By default, module.exports is an empty object : {}

You can replace exports with a function. This will export just that function.

Or you can export many functions, variables, objects, by assigning them to exports. This is what you have done in your question: assigned the function Auction to the property Auction of exports.

Sign up to request clarification or add additional context in comments.

2 Comments

For me it only works if i require('./lib/auction').Auction(); with parentheses, any idea why?
@Tim, In your case, require('./lib/auction').Auction returns a function and you have to call the function to execute it by adding the parenthesis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.