所以我有模块“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.
}
所以我拥有了所有这些,但我的主要应用程序是一个可以控制这个“机器人”的网站(它不是垃圾邮件机器人,而是审核/统计机器人),并且我正在使用 require 函数来使用 “./bot.js” 在“app.js”
app.js
bot = require('./bot');
那么我如何不断地使用 bot.js、app.js 中的数据呢?我对模块的工作原理有点模糊。
是的,我可以把 app.js 的所有内容都放在 bot.js 中,但是浏览起来太烦人了。
谢谢!
最佳答案
将db_users
放入一个对象中,这样它就只是一个引用。请改为更改该引用。然后导出
该外部对象。现在,由于 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
将始终拥有 bot.js
中对 data.db_users
所做的最新更改
关于javascript - 如何在模块之间更新此变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378197/