Skip to content

Instantly share code, notes, and snippets.

@mrvisser
Last active February 11, 2024 23:53
Show Gist options
  • Save mrvisser/7897567 to your computer and use it in GitHub Desktop.
Save mrvisser/7897567 to your computer and use it in GitHub Desktop.
Module circular dependency weirdness
var events = require('events');
var b = require('./b');
var emitter = module.exports = new events.EventEmitter();
module.exports.init = function(callback) {
b.init(function() {
emitter.emit('done');
});
};
var c = require('./c');
module.exports.init = function(callback) {
c.init(callback);
};
var a = require('./a');
module.exports.init = function(callback) {
a.on('ready', function() {
console.log('"a" is now ready! (from c)');
});
callback();
};
var a = require('./a');
a.on('ready', function() {
console.log('this a.on was able to be set');
});
a.init(function() {
console.log('finished main');
});
test-circular$ node main.js
.../test-circular/c.js:5
a.on('ready', function() {
^
TypeError: Object #<Object> has no method 'on'
at Object.module.exports.init (.../test-circular/c.js:5:7)
at Object.module.exports.init (.../test-circular/b.js:5:7)
at EventEmitter.module.exports.init (.../test-circular/a.js:8:7)
at Object.<anonymous> (.../test-circular/main.js:8:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
@mrvisser
Copy link
Author

Explanation:

The reason this error is happening is not because of a circular dependency. Each module a, b and c gets loaded as you would expect.

The reason c.js does not find the on method is because after c.js stores its reference to a.js, a's module.exports value gets reassigned to new events.EventEmitter(). So it's basically just a shared object reassignment issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment