ECMAScript
ECMAScript

Reputation: 4649

How do I update the values of this variable between modules?

So I have module "bot.js" and in this module, it constantly checks for messages and assigns them to a variable (db_users). Since I run my app from "app.js", and I pass the functions that continuously populates db_users, how do I get this information to "app.js"?

Bot.js is using an IRC function that stores user's messages.

var db_users = []
// I then populate db_users with the previous data that is already in mongodb 
// using a .find().exec() mongodb command.
bot.addListener('message', function (from, to, text) {
    userInfo.checkForUser(db_users);
    // checkForUser basically looks through the variable db_users to see if 
    // there is a username that matches the "from" parameter in the listener
    // If it's not there, push some user information into the db_users array
    // and create a new MongoDB record.
    }

So I have all this, but my main app is a website that can control this "bot" (It's not a spam bot, but a moderation/statistical bot), and I'm using a require function to use "./bot.js" in "app.js"

app.js

bot = require('./bot');

So how would I constantly use the data in bot.js, in app.js? I'm a little fuzzy on how modules work.

Yeah I could just put all of the contents of app.js in bot.js, but it would be too annoying to look through.

Thanks!

Upvotes: 0

Views: 89

Answers (1)

laggingreflex
laggingreflex

Reputation: 34687

Put db_users inside an object so that it's just a reference. Make changes to that reference instead. Then export that outer object. Now since db_users is just a reference, it'll always be a latest copy of whatever it refers to.

bot.js

var data = module.exports = {};
data.db_users = [];
bot.addListener('message', function (from, to, text) {
    userInfo.checkForUser(data.db_users);
    }

app.js

botData = require('./bot');

botData.db_users will always have the whatever latest changes were made to data.db_users in bot.js

Upvotes: 1

Related Questions