[node.js] Declare multiple module.exports in Node.js

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?

This question is related to node.js module

The answer is


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

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
    };
}());

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;

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

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);
    }
};

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

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

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);

You can use this approach too

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

or

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

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;
};

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);

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();

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');


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>);

use this

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

  }
  exports.yourMethod2 =  function (success)
  {

  }


})();

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"),
};

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!