2015-02-07 42 views
0

所以我有模块“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),和我使用的是需要功能使用“./bot.js”“app.js”

app.js

bot = require('./bot'); 

所以,我怎么会经常使用bot.js的数据,应用程序.js文件?我对模块的工作方式有些模糊。

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

谢谢!

+0

你有没有了解[ 'module.exports'](http://nodejs.org/api/modules.html#m odules_module_exports)? – laggingreflex 2015-02-07 03:46:08

+0

是的,但我真的不知道如何在这里使用.. – ECMAScript 2015-02-07 03:53:49

回答

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