1

I have the following files.

index.js

module.exports = {
    "first": require('./1.js'),
    "second": require('./2.js'),
    "third": require('./3.js')
};

1.js

module.exports = "Hello";

2.js

module.exports = "World";

3.js

const utils = require('./');
module.exports = `${utils.first} ${utils.second}`;

run.js

const utils = require('./');
console.log(utils.first);
console.log(utils.second);
console.log(utils.third);

Why is it that when I run node run.js that it prints the following?

Hello
World
undefined undefined

I expect it to print

Hello
World
Hello World
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

2 Answers2

1

This is because at the time of running 3.js the index.js file has not been fully defined yet. In order to fix this you have to require the files specifically. For example changing 3.js to the following will work.

const first = require('./1.js');
const second = require('./2.js');
module.exports = `${first} ${second}`;
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • just curious: Is this is how circular dependencies are resolved ? Like with an undefined. By circular dep I mean `index`>`3`>`index` in the question. – trk Sep 19 '18 at 03:19
  • 1
    I think so, yeah. I just ran into a circular dependency type thing. I didn't know it was called that, but yes that sounds like the correct term. This was how I was able to solve it. – Charlie Fish Sep 19 '18 at 03:27
0

Just remove this line:

   "third": require('./3.js')

You cannot make index.js dependend on 3.js as 3.js is dependend on index.js (thats called circular dependency). Nodejs might be able to resolve it some specific cases but I woupd generally not do this. Instead extract the parts that 3.js uses from index.js into a new file, and then import that from both.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151