When you import a variable from another javascript module, you get that variable by value, not by reference (you create a copy of the value at the given memory address, you don't simply get a pointer to that same exact variable). Therefore, you have only mutated the Test
variable in File1.js
; to reflect those changes in your console.log
in File2.js
you would have to re-export your mutated variable from File1.js
and import that into File2.js
, and then do the log.
Here is analysis of your code:
File1.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// pushes 12 to the copy
Test.push(12) // => [10, 11, 12]
File2.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// This interval does nothing. The fact is, the mutated
// `arrays` var from `File1.js` does not effect the
// `arrays` var in any other modules scope.
setInterval(function(){console.log(Test)},2000) // => [10, 11]
This is all assuming you have additional code not seen here that is required and executed from an entry point. As Thomas said in the comments, there is no state persisted between running individual scripts.
To accomplish what you're attempting in your post:
Balances.js:
var arrays = [10, 11]
module.exports = arrays
File1.js:
var test = require('./Balances')
test.push(12)
module.exports = test
File2.js:
var test = require('./File1')
function action() {
console.log(test)
}
module.exports = action
main.js (entry point):
var action = require('./File2')
action() // => [10, 11, 12]
run $ node main.js
Hope this helps!