简体   繁体   中英

Is module.export = [] bad practice?

I have two modules, both of which need to access a shared array. I solve this by having a module which just consists of the following:

sharedArray.js

module.exports = [];

In the modules I use it like this:

module1.js

var arr = require('./sharedArray');

function addSomething() {
    // Add something to arr 
}

module2.js

var arr = require('./sharedArray');

function doSomething() {
    // Use arr for something
}

This works but feels wrong (useless empty module) and that I'm missing something obvious.

Is there a better way to do it or is this actually how you solve it?

It is not a bad practice. It is just one of several options for sharing data among modules. There is nothing "wrong" with doing it the way you are doing it.


When sharing data among modules in node.js, you basically have three choices:

  1. You can have one module that assigns the data to the global namespace when loaded.

  2. You can have a method of some module that returns a reference to the data. The method could be the module constructor or some other method.

  3. You can make the data be part of a static data structure that is in the module exports. This is essentially what you are doing now where you just make the whole exports be your array.

All three are perfectly legitimate ways of sharing the data.

The global data has the typical downsides of using globals (impacts the global namespace and potentially conflicts with a module that isn't even trying to use this particular data).

You could use the 2nd option when you were doing many other things with the module also or if you were generating the data upon demand rather than declaring it statically.

For the third option, if you made the module return an object and had the array be one property in that object that would make your module more extensible because then you could have other shared elements in that module also. But, it works as you have it, it just isn't very extensible.


I personally would probably go for the more extensible option so you could have other shared items there also:

sharedData.js

module.exports = {
    myData: [...],
    myOtherData: [...]
};

module1.js

var arr = require('./sharedData').myData;

function addSomething() {
    // Add something to arr 
}

module2.js

var arr = require('./sharedData').myData;

function addSomething() {
    // Add something to arr 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM