Node modules that instantiate things?

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!

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

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