Skip to content

Instantly share code, notes, and snippets.

@andineck
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andineck/7203604492ef23ee5c40 to your computer and use it in GitHub Desktop.
Save andineck/7203604492ef23ee5c40 to your computer and use it in GitHub Desktop.
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