1

I'm writing a very basic Node app with three components: index.js, mqtt.js, slack.js. The mqtt and slack modules both expose some of their methods with module.exports. However, I can only expose the files in one direction. Code sample:

index.js:

var slack = require('./slack');
var mqtt = require('./mqtt');

var client;

mqtt.connectMQTT(client);
slack.startServer();

slack.js:

var mqtt = require('./mqtt');
module.exports = {
startServer: function() { //blahblah },
postToSlack: function() { //blahblah }
};

mqtt.js:

var slack = require('./slack');
module.exports = {
connectClient: function() { //blahblah },
handleMessage: function() { slack.postToSlack(); }
};

Now, when I try to call postToSlack() from mqtt.js, Node gives me: TypeError: Object # has no method 'postToSlack'

BUT, when I swap the line position of the two require()'s in index.js, now I can call methods from mqtt but not from slack. The error has mirrored itself. I can call methods from index.js just fine.

Should I be using callbacks to hold off running any code until all of my modules have successfully been loaded? Why does the order of require() in a completely separate file affect exposing methods?

kyleburke
  • 269
  • 4
  • 8

1 Answers1

0

You have a circular dependency between slack.js and mqtt.js. Read the node.js docs on require cycles for details, but the correct solution to this situation is usually to remove the circular dependency entirely. It is an indicator that your design coupling is not quite right yet.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274