432

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?

Ali
  • 9,997
  • 20
  • 70
  • 105
  • For anyone coming here wanting to know how to export multiple `require` methods, or a combination of `require` methods and other functions, then the answer is [here](https://stackoverflow.com/a/45408341/197591). – Neo Aug 24 '21 at 22:31

21 Answers21

875

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');
mash
  • 14,851
  • 3
  • 30
  • 33
  • 17
    I'm not using `module.method` anywhere here...only `exports.method`, which is just a reference to `module.exports.method`, so behaves the same way. The only difference is we did not define `module.exports`, so it defaults to `{}`, unless I'm mistaken. – mash Dec 15 '14 at 18:08
  • @mash would this work in another file by using: `var otherMethod = require('module.js')(otherMethod);`? I.e., would that line require the `otherMethod` function just as if it were the only function on the page and the export had been: `module.exports = secondMethod;`? – YPCrumble Jun 29 '15 at 20:51
  • 4
    @YPCrumble you could do `var otherMethod = require('module.js').otherMethod`. – mash Jun 29 '15 at 21:44
232

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
Laurel
  • 5,965
  • 14
  • 31
  • 57
Devorah
  • 2,390
  • 1
  • 9
  • 8
  • 31
    You can also do this when accessing them: `const { function1, function2, function3 } = require("./lib/file.js")` which allows you to call them directly (e.g. `function1` instead of `myFunctions.function1`) – David Yeiser Jun 13 '19 at 15:31
73

in addition to @mash answer I recommend you to always do the following:

const method = () => {
   // your method logic
}

const otherMethod = () => {
   // your method logic 
}

module.exports = {
    method, 
    otherMethod,
    // anotherMethod
};

Note here:

  • You can call method from otherMethod and you will need this a lot
  • You can quickly hide a method as private when you need
  • This is easier for most IDE's to understand and autocomplete your code ;)
  • You can also use the same technique for import:

    const {otherMethod} = require('./myModule.js');

Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
  • 3
    Note that this uses the es6 object initializer shortcut - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer – chrismarx Dec 11 '17 at 20:04
  • 2
    This is the better answer imho as it addresses accessing method form otherMethod. Thanks for pointing that out. – Jeff Beagley May 15 '18 at 21:23
  • 1
    I was looking for how to write ```const {otherMethod} = require('./myModule.js');``` this. what do you call this approach of import methods from a {}? – Franva Aug 18 '20 at 09:52
  • 3
    @Franva When you do `require(./myModule.js)` in the right side of the assignment you are actually importing the whole module as a single object then when you do `const {otherMethod}` in the left side of the assignment you are doing something called "Destructuring Assignment" you can read more about it in MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – Fareed Alnamrouti Aug 19 '20 at 08:52
  • but, what if my methods are async, and I want to call method in otherMethod – Lube Dec 19 '21 at 10:34
  • @Lube you still can do this using normal `await` or `YourPromise.then`, just note that if `method` is async then `otherMethod` also need to be async too so you can call `method` if not still you can do it without `await` but it will be considered anti-pattern – Fareed Alnamrouti Dec 19 '21 at 12:44
29

module.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

main.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);
Anthony Awuley
  • 3,455
  • 30
  • 20
18

This is just for my reference as what I was trying to achieve can be accomplished by this.

In the module.js

We can do something like this

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

      return { firstFunction: firstFunction, secondFunction: secondFunction,
 thirdFunction: thirdFunction };

    }

In the main.js

var name = require('module')(firstArg, secondArg);
evandrix
  • 6,041
  • 4
  • 27
  • 38
Ali
  • 9,997
  • 20
  • 70
  • 105
12

If the files are written using ES6 export, you can write:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};
Jon Sakas
  • 2,042
  • 1
  • 21
  • 26
11

One way that you can do it is creating a new object in the module instead of replacing it.

for example:

var testone = function () {
    console.log('test one');
};
var testTwo = function () {
    console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;

and to call

var test = require('path_to_file').testOne:
testOne();
Alvaro Castro
  • 811
  • 1
  • 9
  • 26
Jesse Teixeira
  • 131
  • 1
  • 4
7

You can write a function that manually delegates between the other functions:

module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};
Duncan Walker
  • 2,182
  • 19
  • 28
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • This is a way to achieve function overloading, but it's not very... elegant. I think Mash' answer is cleaner and better shows intent. – Nepoxx Sep 19 '14 at 17:14
7

There are multiple ways to do this, one way is mentioned below. Just assume you have .js file like this.

let add = function (a, b) {
   console.log(a + b);
};

let sub = function (a, b) {
   console.log(a - b);
};

You can export these functions using the following code snippet,

 module.exports.add = add;
 module.exports.sub = sub;

And you can use the exported functions using this code snippet,

var add = require('./counter').add;
var sub = require('./counter').sub;

add(1,2);
sub(1,2);

I know this is a late reply, but hope this helps!

Achintha Isuru
  • 2,662
  • 18
  • 24
5

use this

(function()
{
  var exports = module.exports = {};
  exports.yourMethod =  function (success)
  {

  }
  exports.yourMethod2 =  function (success)
  {

  }


})();
Siddharth
  • 545
  • 2
  • 7
  • 24
5

also you can export it like this

const func1 = function (){some code here}
const func2 = function (){some code here}
exports.func1 = func1;
exports.func2 = func2;

or for anonymous functions like this

    const func1 = ()=>{some code here}
    const func2 = ()=>{some code here}
    exports.func1 = func1;
    exports.func2 = func2;
bahri noredine
  • 731
  • 9
  • 15
5

You can use like i did below... for both functions and arrow functions :

greet.js :

function greetFromGreet() {
  console.log("hello from greet module...");
}

const greetVar = () => {
  console.log("greet var as a arrow fn/...");
};

module.exports = { greetVar, greetFromGreet }; // ---- multiple module export...

// -----------------------------------------------

app.js :

const greetFromGreets = require("./greet");

greetFromGreets.greetFromGreet();
greetFromGreets.greetVar();

// -----------------------------------------------

Basavaraj SK
  • 245
  • 3
  • 3
4

Inside your node module you can export various functions such as:

module.exports.eat = eat;

function eat() {
  .......
  return *something*;
};

module.exports.sleep = sleep;

function sleep() {
  .......
  return *something*;
};

Note that you are not calling the functions while exporting them. Then while requiring the modules you can require as:-

const task = require(__dirname + "/task.js");
//task is the name of the file

let eat = task.eat();
let sleep = task.sleep();
3

Two types module import and export.

type 1 (module.js):

// module like a webpack config
const development = {
  // ...
};
const production = {
  // ...
};

// export multi
module.exports = [development, production];
// export single
// module.exports = development;

type 1 (main.js):

// import module like a webpack config
const { development, production } = require("./path/to/module");

type 2 (module.js):

// module function no param
const module1 = () => {
  // ...
};
// module function with param
const module2 = (param1, param2) => {
  // ...
};

// export module
module.exports = {
  module1,
  module2
}

type 2 (main.js):

// import module function
const { module1, module2 } = require("./path/to/module");

How to use import module?

const importModule = {
  ...development,
  // ...production,
  // ...module1,
  ...module2("param1", "param2"),
};
illvart
  • 847
  • 9
  • 10
2

module1.js:

var myFunctions = { 
    myfunc1:function(){
    },
    myfunc2:function(){
    },
    myfunc3:function(){
    },
}
module.exports=myFunctions;

main.js

var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module
0

If you declare a class in module file instead of the simple object

File: UserModule.js

//User Module    
class User {
  constructor(){
    //enter code here
  }
  create(params){
    //enter code here
  }
}
class UserInfo {
  constructor(){
    //enter code here
  }
  getUser(userId){
    //enter code here
    return user;
  }
}

// export multi
module.exports = [User, UserInfo];

Main File: index.js

// import module like
const { User, UserInfo } = require("./path/to/UserModule");
User.create(params);
UserInfo.getUser(userId);
Manish
  • 639
  • 6
  • 17
0

You can use this approach too

module.exports.func1 = ...
module.exports.func2 = ...

or

exports.func1 = ...
exports.func2 = ...
Bogdan Surai
  • 1,197
  • 14
  • 16
0

Adding here for someone to help:

this code block will help adding multiple plugins into cypress index.js Plugins -> cypress-ntlm-auth and cypress env file selection

const ntlmAuth = require('cypress-ntlm-auth/dist/plugin');
const fs = require('fs-extra');
const path = require('path');

const getConfigurationByFile = async (config) => {
  const file = config.env.configFile || 'dev';
  const pathToConfigFile = path.resolve(
    '../Cypress/cypress/',
    'config',
    `${file}.json`
  );
  console.log('pathToConfigFile' + pathToConfigFile);
  return fs.readJson(pathToConfigFile);
};

module.exports = async (on, config) => {
  config = await getConfigurationByFile(config);
  await ntlmAuth.initNtlmAuth(config);
  return config;
};
testtek
  • 1
  • 1
0

Use the export keyword

module.js

export {method1, method2}

And import them in main.js

import {method1, method2) from "./module"
Sorter
  • 9,704
  • 6
  • 64
  • 74
0

As others have stated, this would be the preferred way of exporting:

// In foo/bar.js
module.exports = {
    method1: () => {},
    method2: () => {},
};

However, the preferred es6 way of importing from the calling script would look like:

const { method1, method2 } = require('./foo/bar');
Bud Linville
  • 193
  • 1
  • 10
-1
module.exports = (function () {
    'use strict';

    var foo = function () {
        return {
            public_method: function () {}
        };
    };

    var bar = function () {
        return {
            public_method: function () {}
        };
    };

    return {
        module_a: foo,
        module_b: bar
    };
}());