Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sharing variables in modules node.js

Sharing variables in modules node.js

Problem

I understand how exports works, but how can I create a Variable in my main file, and then use that variable in my module? I tried passing my "global" variable to a function in my module, but it passed as a copy, not by reference and since its an array I'm passing that's no good.

For example

# main file
var someObject = {};

var myModule = require('./whatever');
moModule.function_a(someObject);
moModule.function_b(someObject);

Even though someObject is an object it passes by copying, and if I change its value inside function_a or function_b, it wont change in the global scope, or in any other modules where I use it.

Problem courtesy of: Macmee

Solution

If you modify a passed argument, the argument will change outside the function.

However, what you're probably doing that's making you think the object is being copied is you're reassigning the variable.

What you should do:

function foo(a) {
  a.bar = 42;
}
var o = {};
foo(o);
console.log(o); // { bar: 42 }

What not to do:

function foo(a) {
  a = { bar: 42 };
}
var o = {};
foo(o);
console.log(o); // {}
Solution courtesy of: fent

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sharing variables in modules node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×