Skip to content

Instantly share code, notes, and snippets.

@andineck

andineck/1 readme.md

Last active Aug 29, 2015
Embed
What would you like to do?
shared module

node.js module hickups

modules in node are great. sharing them in npm is even better.

  • make sure you understand, that module when you require the same module from within the same directory, you get the reference to the same thing.
  • if you require the same module in files wich are located in different directories, you get two new module instances.

run

node b.js
var c = {
a: 1,
b: 2
};
module.exports = function() {
};
module.exports.set = function(key, val) {
c[key] = val;
};
module.exports.print = function() {
var json = JSON.stringify(c, null, 2);
console.log(json);
};
var a1 = require('./a');
a1.set('b', 22);
a1.print();
var a2 = require('./a');
a2.print();
a2.set('c', 33);
a1.print();
/*
ouput:
{
"a": 1,
"b": 22
}
{
"a": 1,
"b": 22
}
{
"a": 1,
"b": 22,
"c": 33
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment