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

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

本文关键字:变量 更新 之间 模块      更新时间:2023-09-26

所以我有一个模块"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函数在"app.js"中使用"./bot.js"

app.js

bot = require('./bot');

那么,我该如何不断地使用bot.js和app.js中的数据呢?我对模块的工作方式有点模糊。

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

谢谢!

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将始终具有bot.js 中对data.db_users进行的任何最新更改