0

Let's say I have module A.js and B.js.

A.js

var b = require('./B'); [...some code here...] 

B.js

var a = require('./A'); [...some code here...] 

than in my app.js I have something like:

app.js

var a = require('./A'); [some code here] 

The thing is that the var a in B.js is always an empty object {} when I do like node app.js while If I directly do node B.js it is properly initialized.

What instead I would expect is that calling node app.js it triggers A.js (that requires B.js) and so, in turn it initialtes its own a variable.... but it is not like this apparently....

1 Answer 1

2

You've got a circular module dependency, so the sequence goes like this:

  1. app.js requires A
  2. A requires B
  3. B requires A (which is not completely defined yet)

In step 3, B gets the definition of A at the time of the require. That's just an empty object at that point so that's what a gets set to in B.js.

Sign up to request clarification or add additional context in comments.

1 Comment

yeha, I think so too... thanks for the link and the information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.