Export objects vs functions NodeJs Export objects vs functions NodeJs node.js node.js

Export objects vs functions NodeJs


How do you understand in your design of a module, when is appropriate to exports, an object, anonymous function, named function to Instantiate?

  • true minimalists aim to export a single function if that will suffice. This is based on the scope of your module and assumes a small and focused purpose.
  • Export an object of related functions when you need a set of functions to have a meaningful set of functionality. For example, a tempConversion module might have both cToF and fToC functions.
  • If you are doing OO, exporting the constructor function is fine.
  • a closure function that returns the real payload (which can be an object or a function) is useful for configuration options. For example var tip = require('computeTip')(18); could store 18 in closure and return a function that would calculate 18% tip when called with a number.

Here's a rule of thumb: if you export only one named function a la require('average').average(listOfNumbers), it's redundant, so just export the average function directly to make it more concise. If you have more than one function you want to expose, use an object whose properties are the functions.

Which are the difference and how the require method behave, when requiring these functions or Objects ?

  • There are no differences. require has a single behavior that accommodates each of these techniques.


In both your examples you actually return an object and not a function class. In the second case you get the object by executing the function. In order to use the function as a class you should return a function which acts as the constructor, and then instantiate with the new operator.

That being said, I would prefer an object over a class if I consider my module as a singleton, something that would be common to every file that would include it. An example would be a module that implements a common access layer to my database.

A class makes more sense if you intent to instantiate it multiple times. An example would be a specific model class for your database schema, like a User class.