0

I have been reading about Node's require and how its exports is automatically overridden when a module.exports has data or functionality declared within it. So let me see if I understand correctly: anything that I put in exports will be included in files which require the file.

I have inherited some node files, one main file with heaps of requires, and each required file with the structure:

var obj = {};
obj.prop1 = "some value1";
obj.prop2 = "some value2";    
module.exports = exports = obj;

Is this a standard way of exporting data in a required file? Is it sensible to a)declare this (seemingly redundant obj)? ,b)if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj? c)what is the purpose of this middle-level exports if it can be overridden? What is the use case for both of these objects?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

1

what is the purpose of this middle-level exports if it can be overridden?

exports is initially set to the value of module.exports and is available as a convenience (and default value), so that you don't have to create your own object to export values. Your example is basically equivalent to just using:

exports.prop1 = "some value1";
exports.prop2 = "some value2"; 

if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj

If you want to export obj from the module, you have to assign it to module.exports. That's how Node knows which value to return when the module is required.

The assignment to exports is not really necessary, but it can prevents mistake like

module.exports = {foo: 42};
// now `module.exports` and `exports` point to different objects
// the following export is just "lost" (ignored)
exports.bar = 21;

The assignments (module.exports = exports = ...) ensures that both, module.exports and exports point to the same object so mutations via either variable have an effect.

Is it sensible to declare this (seemingly redundant obj)

There multiple ways to achieve what you want. I showed one at the top using exports directly. You could also just write

module.exports = {
  prop1: "some value1",
  prop2: "some value2" 
};

Use whatever makes sense to you and complies with the style guidelines you are following.


At the end of the day, the value you want to export must be assigned to module.exports. How you do that is up to you.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143