Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare multiple module.exports in Node.js

Tags:

node.js

module

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?

like image 829
Ali Avatar asked May 19 '13 03:05

Ali


People also ask

Can we have multiple module exports?

You can export as many functions as needed as long as you remember that there can be only one default export. The default export in JavaScript is used to export a single/fallback value from a module. With a default export, you do not need to specify a name for the exported function.

How do I export multiple functions?

To export multiple functions in JavaScript, the easiest way to do so is by using the export statement before each function you want to export. As long as you do not export functions as default then you can export as many functions as you like from a module.


2 Answers

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');
like image 62
mash Avatar answered Oct 13 '22 14:10

mash


To export multiple functions you can just list them like this:

module.exports = {
   function1,
   function2,
   function3
}

And then to access them in another file:

var myFunctions = require("./lib/file.js")

And then you can call each function by calling:

myFunctions.function1
myFunctions.function2
myFunctions.function3
like image 217
Devorah Avatar answered Oct 13 '22 15:10

Devorah