Declare multiple module.exports in Node.js

Ali picture Ali · May 19, 2013 · Viewed 303.3k times · Source

What I'm trying to achieve is to create one module that contains multiple functions in it.

module.js:

module.exports = function(firstParam) { console.log("You did it"); },
module.exports = function(secondParam) { console.log("Yes you did it"); }, 
// This may contain more functions

main.js:

var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);

The problem I have is that the firstParam is an object type and the secondParam is a URL string, but when I have that it always complains that the type is wrong.

How can I declare multiple module.exports in this case?

Answer

mash picture mash · May 19, 2013

You can do something like:

module.exports = {
    method: function() {},
    otherMethod: function() {},
};

Or just:

exports.method = function() {};
exports.otherMethod = function() {};

Then in the calling script:

const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');