1

Can I build a module that exports instantiated variables?

Module:

var module1 = require('module1')
var Module2 = require('module2')

module1.dosomething(variables)
exports.module1 = module1

//or

module2 = new Modle2(variables)
module2.dosomething(variables)
exports.module2 = module2

Can I require the module above in many other files and use the exports as instantiated variables or will they be re-instantiated every time I require them and not shared between the files requiring them.

Thanks!

skaffman
  • 398,947
  • 96
  • 818
  • 769
fancy
  • 48,619
  • 62
  • 153
  • 231
  • You can do either. Not a good answer. It depends on how you want to do it. – Jamund Ferguson May 18 '12 at 21:53
  • I can do both of those and the exports wont be re-instantiated versons of module1 and module2 each time they are required? The exports will always refer to the already instantiated versions? – fancy May 18 '12 at 21:55
  • It depends, but yes, see my answer to this other question http://stackoverflow.com/questions/8931239/how-to-access-variables-declared-in-main-app-js-in-seperate-route-files-in-node/8931366#8931366 – Jamund Ferguson May 18 '12 at 21:56

2 Answers2

3

Your example is confusing because you use module1 in multiple contexts, both as a module, a variable within another module, and an exported property of that module.

Think of modules as closures and exports as return values. Most likely you want to export a function/factory function and call that every time if you want to create new instances with the export, anything else will be shared since it just returns the object.

Module1

module.exports.var1 = function(opts) {
    // do stuff
    return variables;
};

module.exports.var2 = new Blah(); // single instance

Other module

var var1 = require('module1').var1({ opt1: 'foo' }); // New instance every time
var var2 = require('module1').var2; // Same var instance even if you include in another module
kmiyashiro
  • 2,249
  • 14
  • 15
1

You can even do things like this to be really annoying. Most npm modules make you create instantiated versions to avoid this kind of silliness.

// file.js
var m1 = require('./m1');
m1.awesome = false;
console.log("I am awesome", m1.awesome);

// file2.js
var m1 = require('./m1');
console.log("I am awesome", m1.awesome);

// both.js
require('./file');
require('./file2');

// m1.js
exports.awesome = true;

now run this:

node file1.js
I am awesome false

node file2.js
I am awesome true

node both.js
I am awesome false
I am awesome false
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • 1
    This basically means in both.js the file1's operations polluted file2 operations right? Meaning we should always export objects that can be instantiated? – CMCDragonkai Mar 06 '14 at 13:58
  • If you return a new object either by doing `new` or by using the factory pattern then yeah you can't collide. – Jamund Ferguson Mar 06 '14 at 17:54