0

I have a web-project for browser written with help of browserify to get power of npm packages. In one file i am creating array with data that i need to use in another module.

//a.js
var arr = require('./b.js')

module.exports = function () {
    console.log('from a.js');
    console.log(arr);
}
//b.js
var a = require('./a.js')
var array = [1,2,3,4,5,6];

a();

console.log('from b.js');
console.log(array);

module.exports = array;
//main.js
require('./b.js');

[A] and [B] need to require each other(that causes access problems to array i guess). But i need [A] to require [B] to get array and [B] require [A] to get some functionality. And in main.js i need only to require [B]. So require logic scheme goes like this:

Main.js requires [B] (that has array and uses functionality of [A]) requires [A] (that get access to [B] to get array and return some functionality)

Main > [B] <> [A]

problem is that array in [A] is empty object {}

Anton
  • 516
  • 1
  • 6
  • 22
  • 2
    Possible duplicate of [How to deal with cyclic dependencies in Node.js](https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js) – apple apple May 06 '19 at 09:36
  • 1
    move `require('./a.js')` down and `module.exports = array;` up may solve the problem, but you'd better restructuring your code – apple apple May 06 '19 at 09:37
  • 1
    To quote the [docs](https://nodejs.org/api/modules.html#modules_cycles): "In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module." –  May 06 '19 at 09:41
  • thx guys a lot. helped me understand problem in more advanced way. – Anton May 06 '19 at 09:42

0 Answers0