Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js object is not a function - module.exports

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)

like image 912
dzm Avatar asked Mar 27 '12 16:03

dzm


People also ask

How do I export an object in node JS?

The module.js is used to export any literal, function or object as a module. It is used to include JavaScript file into node. js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module.

CAN module exports be a function?

Note: By default, exports is an object, but it can also be a function, number, string, etc.

What is the use of module exports in node JS?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.


1 Answers

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.

like image 200
The Who Avatar answered Oct 25 '22 14:10

The Who