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?