0

I currently have a program structured like the minimal example below. I have object foo which has method addColor, which requires module bar.

bar requires baz and passes the parameter color.

baz requires foo to edit a property from foo (addColor must add a color to foo.colors)

However inside baz: foo returns {} and the following error occures.

foo.colors.push(color);
           ^

TypeError: Cannot read property 'push' of undefined

I imagine this is an issue with module recursion and cannot find a work-around to this problem without possibly restructuring my program.

index.js

const foo = require('./foo');

console.log(foo);
// { colors: [ 'red', 'green' ], addColor: [Function (anonymous)] }

foo.addColor('blue');

foo.js

module.exports = {
  colors: ['red', 'green'],
  addColor: require('./bar')
}

bar.js

const baz = require('./baz');
module.exports = color => {
  baz(color);
};

baz.js

const foo = require('./foo');
module.exports = color => {
  console.log(foo); // {}

  foo.colors.push(color);
  /*
    foo.colors.push(color);
               ^

    TypeError: Cannot read property 'push' of undefined
  */
};
Elitezen
  • 6,551
  • 6
  • 15
  • 29

1 Answers1

1

You have a cycle in your dependency graph. That's likely to cause problems. See this question for some ideas on how to resolve the problem: How to deal with cyclic dependencies in Node.js

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • Thanks for the info, however I ended up making `foo` a global environment variable. I'll mark my question as a duplicate to the thread you've linked. – Elitezen Jul 06 '21 at 21:31