allen allen - 1 month ago 7
Node.js Question

Node.js change value from required object

--- main.js ---

var myModule = require('./module_a.js');
var value = 0;

myModule.set(35);
console.log("myModule.data:", myModule.data);
console.log("myModule.get():",myModule.get());
console.log(myModule);


--- module_a.js ---

exports.data = 10;
exports.set = function(value) {
data = value;
};
exports.get = function() {
return data;
};


I have expected that the
main.js
's result is 35 each in 2
console.log()
. But, the result is 10 each.

I don't know why this happens. From
require
method, variable
myModule
is a object which has
data
, function
set
, function
get
.

So,
myModule.set(35)
should have to change
myModule
object's data to 35. But, it is still 10.

If I use
this.data = value
and
return this.data
. It works as I expected. But not in the first case(my above source code)

Why this happen??

Answer

You don't have a local data variable in your module.

Try changing this line

exports.data = 10; 

to

var data = 10;
exports.data = data;