如何在模块之间更新此变量的值?

时间:2015-02-07 03:24:11

标签: javascript node.js mongodb

所以我有模块“bot.js”,在这个模块中,它不断检查消息并将它们分配给变量( db_users )。由于我从“app.js”运行我的应用程序,并且我传递了连续填充 db_users 的函数,如何将此信息提供给“app.js “

Bot.js 正在使用存储用户消息的IRC功能。

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.
    }

所以我有这一切,但我的主要应用程序是一个可以控制这个“僵尸”的网站(它不是垃圾邮件机器人,而是一个审核/统计机器人),我正在使用一个需要的功能来使用“./ bot.js”“app.js”

app.js

bot = require('./bot');

那么我如何在app.js中经常使用bot.js中的数据?我对模块的工作原理有点模糊。

是的,我可以把app.js的所有内容都放在bot.js中,但是看起来太烦人了。

谢谢!

1 个答案:

答案 0 :(得分:1)

db_users放在对象中,以便它只是一个引用。改为对该引用进行更改。然后export那个外部对象。现在,因为db_users只是一个引用,所以它始终是它引用的最新副本。

<强> 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将始终拥有data.db_users

中对bot.js所做的最新更改