Reloading / Reinitializing / Updating CommonJS Modules

My understanding is that CommonJS modules are meant to be loaded once. Let's say we have a one page application with hash based navigation, when we go to a previously loaded page, the code doesn't restart as it has already been loaded once, which is what we want.

How can I load the contents of a module as if it hadn't been initialized yet? For example, if I have some data in local storage that is changing, how can I run a function to update that data and / or what would be the best way to update this data in a previously loaded module?

0


source to share


1 answer


Instead of directly exporting the content of your module, you can simply wrap it in a function and then call that function whenever you need that content. I use this template for any initialization a module might need. Here's a simple (and silly) example:

// this module will always add 1 to n
module.exports = function(n) {
  return 1 + n;
}

      

against



module.exports = function(n1) {
  // now we wrapped the module and can set the number
  return function(n2) {
    return n1 + n2;
  }
};

var myModule = require('that-module')(5);
myModule(3); // 8

      

And another example that contains data change:

// ./foo
module.exports = {
  foo: Date.now()
};

// ./bar
module.exports = function() {
  return {
    foo: Date.now()
  };
};

// index.js
var foo = require('./foo');
var bar = require('./bar');

setInterval(function() {
  console.log(foo.foo, bar().foo);  
}, 500);

      

+1


source







All Articles