0

I have a folder src/config in which I have multiple files a.js, b.js, c.js and index.js

When inside b.js I do

const data = require('./index');

OR

const data = require('./index.js');

I always get an empty object which is really strange

// index.js

module.exports = {
  a: require('./a'),
  b: require('./b'),
  c: require('./c')
}

And I am using this index.js and it works just fine.

So, what I have understood from this is that requiring ./index always returns empty object

Can anyone explain this?

d_bhatnagar
  • 1,419
  • 1
  • 12
  • 20

2 Answers2

1

Your issue comes from your approach, you require b.js in index.js where you require b again and so on.

If you require index in a other file, it shoud work as expected.

app.js

const data = require('src/index');
//data.b.foo = "foo"
src/index.js

module.exports = {
    a: require('./a'),
    b: require('./b'),
    c: require('./c')
  }
src/b.js

module.exports = {
    foo:"foo"
}
Quinox
  • 573
  • 3
  • 14
0

what you do cause circular dependency.

First, node loads index.js then loads a.js,b.js and c.js.

when b.js is loaded, node loads index.js in which is required.

node finds that index.js is loading.

node will return an empty object in b.js in order to prevent circular dependency.

Olympiloutre
  • 2,268
  • 3
  • 28
  • 38
charliemei
  • 11
  • 2