In app.js file:
const tempStore = require("./tempStore.js");
setInterval(() => {
tempStore.setTemp(1);
console.log(tempStore.temp); // I expect this will log 1 then 2 then 3 so on...
}, 1000);
In tempStore.js file:
let temp = 0;
const setTemp = num => {
temp += num;
}
module.exports = {
temp: temp,
setTemp: setTemp
}
I expect this line console.log(tempStore.temp); will give me a sequence of increasing number:
1
2
3
4
...
...
But it gives me this:
0
0
0
0
..
..
In other words always 0.
I can find another way to get what I expect by modifying this code:
In app.js file:
const number = tempStore.setTemp(1); // store returned value in a constant
console.log(number); // show it
In tempStore.js file:
temp += num;
return temp; // return the result
But I prefer to get the number directly from temp, why this can't be done?
As far as I remember I can do this while coding in front-end development between .js file. But why I can't do this in NodeJS, what's wrong?
export.tempis not the same astempYou should be using a getter.