Yu Chen
Yu Chen

Reputation: 7490

exporting multiple objects in Node.JS

I'm working on a MEAN stack project, and trying to pass a set of variables from one controller to another. My current approach is to export multiple objects for my **artworks.js** controller file:

module.exports = {
  Router: router,
  artists: distinctArtistsArray
}

The router object is a traditional Express router, but the distinctArtistsArray is a String array of all artists in my MongoDB database. I have an asynchronous function running in the background that every now and then populates distinctArtistsArray. This array is then passed into some other functions written elsewhere in order to do some NLP tasks behind the scenes.

I'd like another controller to have access to these variables as well, since I don't want to be placing undue load on my MongoDB by making duplicate async queries for artist information. Here's my other controller (complete.js):

router.get("/", (req, res) => {
    var ArtworkSearch = require('../controllers/artworks.js');
    console.log(ArtworkSearch.artists)
});

I've placed the require('../controllers/artworks/js') inside the callback function since I want to continuously reimport the values each time a request hits the /complete endpoint.

However, in my console, I receive an empty array ([]), which is what I initialize distinctArtistsArray to. FYI, I've followed the same exact method as the accepted answer in this SO post on a similar topic.

How do I get my list of artists to become available inside complete.js controller?

Upvotes: 0

Views: 2223

Answers (1)

Sven
Sven

Reputation: 5265

The problem is that required modules in NodeJS are cached. From Node's documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

So you don't need to require the file again if you want the updated value, and you can move it outside the request callback.

You should instead export a function that returns the array, like this:

module.exports = {
  Router: router,
  artists: function () {
    return distinctArtistsArray
  }
}

and then

console.log(ArtworkSearch.artists())

You could also manually update the exported value in your code that periodically updates the distinctArtistsArray by running:

module.exports.artists = distinctArtistsArray

This needs to be done every time you update the distinctArtistsArray.

Upvotes: 1

Related Questions