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

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

所以我拥有了所有这些,但我的主要应用程序是一个可以控制这个“机器人”的网站(它不是垃圾邮件机器人,而是审核/统计机器人),并且我正在使用 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/

相关文章:

java - 如何查询一对一的Squillions

javascript - 基本 JS - innerHTML 仅内联工作

javascript - 查询/JavaScript : Is possible to know when page is focussed?

javascript - 需要有关 Function.__proto__ 的 JavaScript 技术解释吗?

node.js - 在哪里可以找到VSCode版本与Electron版本匹配的表?

ruby-on-rails - 学习RoR和Mongo,为什么不统计数组的票数

javascript - 调用 FB Credits API 时出现错误 1151

node.js - 将 AngularJS 应用程序部署到普通 Apache HTTP 服务器是一种常见的选择吗?

node.js - 运行 npm link 时跳过 npm install

javascript - MongoDB:为什么 Array.find on comments(数组)属性返回未定义?