Monday 8 May 2017

Reset module every time certain function is called

const init = require('./init.js');

module.exports = function() {
  // init (or reset if not first time called)
  const caches = init();

  // other code but whats important is that caches are initialized
  // now (or reset) and available from other files via require()
}


// function in init.js (another file)
module.exports = function() {
  return {
    userCache: new Cache('Users'),
    postCache: new Cache('Posts')
  };
}

It doesn't really matter here what Cache() is, what's important is that I need to initlialize them (or reset if called after first time) only in first function and to be able to require() initlialized caches from every other file without resetting them. First function is always called first.

Is this possible with modules? How should my init.js look like to get that behaviour?


I need to make sure that caches are not shared. Like I said, first function always runs first, if I manage to reset the cache from there and not cache it as a module for other requests (Im pretty sure that's something Node does), I would be set.



via Solo

No comments:

Post a Comment