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');
Answer from mash on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ node-module-exports-explained-with-javascript-export-function-examples
Node Module Exports Explained โ€“ With JavaScript Export Function Examples
February 17, 2021 - The above object basically describes an encapsulated module from a JS file with module.exports being the exported component of any types - object, function, string, and so on.
Discussions

Exporting multiple functions in a module
You're trying to set module.exports to two different values. What you want to do is instead export an object with your two functions as props: Module.exports = { myModule, myModules, }; Then you'll be able to import them separately or invoke as props. More on reddit.com
๐ŸŒ r/node
3
2
May 11, 2018
Nodejs - how group and export multiple functions in a separate file?
How can I group and export multiple functions in nodejs? I am trying to group all my util functions in utils.js: async function example1 () { return 'example 1' } async function example2 () ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Exporting multiple functions with arguments
You're making it more complex than needed. Once you have your functions defined, you can export it with this: ... What you're exporting from the module is an object (which I've named init in the example above) that contains two functions. More on stackoverflow.com
๐ŸŒ stackoverflow.com
node.js - NodeJS Module Exports: Export multiple functions vs Exporting a single function - Code Review Stack Exchange
A fourth option which I will call ... "setter" function that takes a property name and a value. // default values for options let defaultOptions = { optionA: defaultValA, optionB: defaultValB, optionC: defaultValC, optionD: defaultValD, optionE: defaultValE }; module.exports.setProp = ... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
July 25, 2018
๐ŸŒ
Softwareshorts
softwareshorts.com โ€บ how-to-export-multiple-functions-in-javascript
How to export multiple functions in JavaScript | SoftwareShorts
And lastly, if you cannot use ES6 then you can use module.exports like so: 1const add = (a, b) => a + b; 2const multiply = (a, b) => a * b; 3const divide = (a, b) => a / b; 4 5module.exports = { add, multiply, divide }; In summary, there are many ways to export multiple functions in JavaScript but all of them will make use of the export statement or module.exports.
๐ŸŒ
Stackify
stackify.com โ€บ node-js-module-exports
Node.js Module Exports - Demystified - Stackify
July 8, 2024 - But why does our module wrapped in a function even matter? Because the moduleโ€™s object is simply an argumentโ€”an object, in this caseโ€”to our module that we can manipulate as we please. Below is an example of how that module object looks: { id: '.', exports: {}, parent: null, filename: '/test.js', loaded: false, children: [], paths: [ '/Users/lbichard/Desktop/node_modules', '/Users/lbichard/node_modules', '/Users/node_modules', '/node_modules' ] }
๐ŸŒ
Reddit
reddit.com โ€บ r/node โ€บ exporting multiple functions in a module
r/node on Reddit: Exporting multiple functions in a module
May 11, 2018 -

Hello I was just wondering if any of you guys could help me with this problem Im having. I have a module.js which has 2 functions MyModule and MyModules. I would like to output both of these functions on a console but if keeps giving me an error:

let foo = moduleTest.testModule(); ^

TypeError: moduleTest.testModule is not a function

I am able to get one function to output to the console but not both.

Module.js:

function myModule(){     let foo = [];    foo.testModule = function(){         foo.push('one');         foo.push('two');     }    return foo; } module.exports = myModule;

function myModules(){
        let foos = [];
       foos.testModules = function(){
            foos.push('one');
            foos.push('two');
        }
       return foos;
    }

module.exports = myModules;

module-import.js:( here is where I try and output both functions)

let MyModule = require('./module');

let moduleTest = new MyModule();

let foo = moduleTest.testModule();

console.log('foo is ' + moduleTest);

//importing the second method

var MyModules = MyModuleos.MyModules;

let moduleTests = new MyModules();

let foos = moduleTests.testModules();

console.log('foo is ' + moduleTests);

For some reason it is not working for me. Any help that you guys could offer is greatly appreciated.

๐ŸŒ
Atomizedobjects
atomizedobjects.com โ€บ blog โ€บ javascript โ€บ how-to-export-multiple-functions-in-javascript
How to export multiple functions in JavaScript | Atomized Objects
August 27, 2021 - 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.
Find elsewhere
๐ŸŒ
Ronald James
ronaldjamesgroup.com โ€บ article โ€บ exporting-multiple-items-from-a-module
Exporting Multiple Items From A Module | Ronald James
Now the count property of this module.exports object will be containing the function definition of our counting function. And therefore, in this way, we can add other properties for including all other functions in our utility module.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ how-to-use-module-exports-in-node-js
How to use module.exports in Node.js
July 8, 2024 - For example, if we would like to export a variable named temperature, we could make it available for use outside the module by simply adding it as a new property of module.exports as follows: ... Now that we have seen the conceptual meaning of a module, as well as why we use modules, let's put into practice these ideas by actually creating a module, defining functions, and then exporting those functions so that they can be used by other modules.
๐ŸŒ
TutorialsTeacher
tutorialsteacher.com โ€บ nodejs โ€บ nodejs-module-exports
Node.js Export Module
In the above example, we have attached a property SimpleMessage to the exports object. Now, import and use this module, as shown below. ... In the above example, the require() function will return an object { SimpleMessage : 'Hello World'} and assign it to the msg variable.
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ understanding module.exports and exports in node.js
Understanding module.exports and exports in Node.js โ€” SitePoint
January 29, 2024 - Then in the index.js file, weโ€™re importing this function and executing it. Also notice that in the require statement, the module name is prefixed with ./, as itโ€™s a local file. Also note that thereโ€™s no need to add the file extension. We can export multiple methods and values in the same way:
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ module-exports-how-to-export-in-node-js-and-javascript
module.exports โ€“ How to Export in Node.js and JavaScript
April 25, 2022 - The exports keyword is a reference to the exports object in the modules object. By doing exports.value1 = value1, it added the value1 property to the module.exports object, as you can see in the first log. The second log does not contain the value1 export anymore. It only has the function exported using module.exports.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ export
export - JavaScript - MDN Web Docs
This is often useful when creating a single module concentrating various exports from various modules (usually called a "barrel module"). This can be achieved with the "export from" syntax: ... Which is comparable to a combination of import and export, except that function1 and function2 do not become available inside the current module:
Top answer
1 of 1
1

Which one is a better approach to setting up variables in NodeJS? (faster, easier to maintain, not an antipattern)

Evaluating the merit of different options depends upon these factors:

  1. How many total options are there now?
  2. How likely are you to add more options as time goes?
  3. Does the caller always set all the options at once? Or is there value to being able to set just some options
  4. Does the caller usually just set one option?

Evaluating each of these:

Total number of options

First off, if you have lots of variables, then neither A or B are particularly practical. A is not very practical because you have to make a separate API for every variable when they're all really just doing the same thing, but for a slightly different property. That's generally not a good thing in an API design.

For lots of variables, option B ends up having to list out a lot of different values all in some precise order and that's not easy to use without having the doc page open every time you want to use it and it's not all that easy to read code that's written to use it either because the reader won't remember which position every single parameter is.

Extending to add more options in the future

Both A and B require modifying the API to extend and add more options. Option A requires adding and documenting a new API entry point. Option B requires adding and documenting a parameter and then making sure that prior code that doesn't include the new parameter isn't broken (by detecting the missing parameter on the receiving end of things). Neither is ideal.

Does the caller always set all options at once

If so, option A is a pain.

Does the caller usually set just one option or a small number of options

If so, option B is a pain.

Do, what you find is that neither option A or option B is entirely flexible for different types of calling usage or extensibility or use with lots of options.

Option C

So, I'll propose using a single options object to be a lot more flexible for different types of calling usage and infinite extensibility without changing the API surface itself. This is also trivial to maintain. Let's call this option C.

// default values for options
let defaultOptions = {
    optionA: defaultValA, 
    optionB: defaultValB, 
    optionC: defaultValC, 
    optionD: defaultValD, 
    optionE: defaultValE 
};

module.exports.setOptions = function(options) {
    // copy any properties from the options object to the default options
    //   overwriting default values with new values
    Object.assign(defaultOptions, options)
}

Or, in some cases, you want to prevent adding anything to defaultOptions that isn't already there (no additional properties allowed):

module.exports.setOptions = function(options) {
    // Copy any properties from the options object to the default options
    //   overwriting default values with new values
    // Only allow copying of properties that are already in defaultOptions
    for (let prop of Object.keys(options)) {
       if (Object.hasOwnProperty(defaultOptions, prop)) {
           defaultOptions[prop] = options[prop];
       }
    }
}

And, the caller would do something like this:

m.setOptions({
    optionC: "someNewValue",
    optionE: "anotherNewValue"
});

Where they can include only whatever options they want to set and they are named options so even if there were 1000 options and you just wanted to set 2 of them, it works quite cleanly.

For extensibility, option C wins every time because it can be extended by simply documenting that you now accept another property name without changing the surface of the API at all.


Option D

A fourth option which I will call option D, is to just have one "setter" function that takes a property name and a value.

// default values for options
let defaultOptions = {
    optionA: defaultValA, 
    optionB: defaultValB, 
    optionC: defaultValC, 
    optionD: defaultValD, 
    optionE: defaultValE 
};

module.exports.setProp = function(propName, value) {
    defaultOptions[propName] = value;
    return this;
}

This allows you to have one single function that could even be chainable that can set any property.

m.setProp("optionC", "someNewValue").setProp("optionE", "anotherNewValue");

This is probably better than option A if everything is just property name and value because it's more extensible without modifying the API, but it's a pain to use if you're trying to set a lot of properties (where option C excels).


Review

For option A, it's really only practical or best if you have a small number of options (say less than 5) and the caller is typically not setting multiple options (typically only setting one option). Even then, I probably still prefer option C as its infinitely extensible without adding more entry points to the API.


For option B, it's really only practical or best if you have a small number of options (say less than 5) and the caller is always setting all the options (or at most leaving off the last one or two). Option B is complicated to use and read if there are lots of options (because you have to remember the right position in the parameter list for each option) and it's complicated to overload to only pass some options. The best part of option B is that with a small number of options, it's probably the least typing for the caller, but that lesser typing means it's less self documenting than the object with named properties in option C.


For option C, it's infinitely extensible and flexible for any type of caller use from setting one property to setting hundreds of properties. And, it's trivial to maintain, even as you add more options. This is generally my preferred choice anytime I have 3 or more options or value extensibility or flexibility in how it's used by the caller.


For option D, I don't personally find it cleaner than option C, but it is flexible and extensible, though inefficient for setting a bunch of options.

๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ the-ultimate-guide-to-react-export-multiple-functions
React Export Multiple Functions
October 22, 2024 - To export multiple functions, simply use the export keyword before each function declaration. This allows you to maintain multiple functions within the same module without having to default to a single export.
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ frequently asked questions โ€บ javascript faq
Can I export more than one object using module.exports?
November 28, 2018 - Answer We can export more than one object using module.exports by giving the object we export properties that are assigned to objects, a few examples: Creating an object to export where the properties are assigned to other objects: let MainObject ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ difference-between-module-exports-and-exports-in-node-js
Difference between module.exports and exports in Node.js | GeeksforGeeks
September 16, 2024 - // Filename: calculator.js class Arithmetic { constructor(a, b) { this.a = a; this.b = b; } add() { return this.a + this.b; } subtract() { return this.a - this.b; } multiply() { return this.a * this.b; } divide() { if (this.b != 0) { return this.a / this.b; } return "divided by zero !!!!"; } }; module.exports = Arithmetic; ... // Filename: operation.js const Arithmetic = require("./calculator.js"); const op = new Arithmetic(100, 40); console.log(`Addition -> ${op.add()}`); console.log(`subtraction -> ${op.subtract()}`); console.log(`Multiplication -> ${op.multiply()}`); console.log(`Division -> ${op.divide()}`); Run the operation.js file using the following command: ... When we want to export multiple variables/functions from one module to another, we use exports.