Reputation: 2457
I'm wondering what would happen if you have two files which require each other. Let's say foo.js
& bar.js
which both require each other. What would happen? Can nodejs figure this out or will it loop endlessly requiring each other?
e.g.
bar.js
const Foo = require('./foo.js`);
const bar = () => {
Foo.foop();
}
const baz = () => {
}
module.exports = {
bar,
baz,
}
foo.js
const Bar = require('./bar.js`);
const foo = () => {
Bar.baz();
}
const foop = () => {
}
module.exports = {
foo,
foop,
}
Upvotes: 2
Views: 358
Reputation: 8773
This is called cyclic require
in Node.js. When there are circular require() calls, a module might not have finished executing when it is returned.
Consider this situation:
a.js:
console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');
b.js:
console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
console.log('b done');
main.js:
console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.
By the time main.js has loaded both modules, they're both finished. The output of this program would thus be:
$ node main.js
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done = true, b.done = true
Careful planning is required to allow cyclic module dependencies to work correctly within an application. Check here for more details.
I would recommend checking this thread as it provides some patterns to follow.
Upvotes: 3