【问题标题】:Is there an way to create an variable which is usable over multiple files (Node.JS)有没有办法创建一个可用于多个文件的变量(Node.JS)
【发布时间】:2019-07-09 15:47:03
【问题描述】:

我正在开发一个不和谐的机器人,我有一个重新启动的 var,默认情况下为 false,如果它设置为 true,它应该在我的日志中打印另一条消息, 现在有办法创建一个全局变量

我有一个 bot.js,我在其中调用我的导出模块(在本例中的另一个文件中 core.js 重新启动,并且在重新启动时我想将重新启动设置为 true,然后在 bot.on 中再次在我的 main 中使用它( “断开连接”)

【问题讨论】:

  • 请阅读how to askmake a minimal example。添加部分代码以澄清您的问题并让某人轻松回答。问题越清楚,答案就越好
  • 下次会做

标签: node.js discord discord.js


【解决方案1】:

将变量添加到 module.exports(在 bot.js 中),这样就可以了

module.exports = {whateveryouhadbefore, restarted}

然后您使用

访问它(在 core.js 中)
const bot = require("./bot");

restarted = bot.restarted;

【讨论】:

  • 刚刚看到编辑,但是我可以编辑导出的变量吗?,因为我需要检查 bot.js 中 restarted 的值并在 core,js 中更改它
  • 您可能会重新考虑您的设计。例如,将 restarted 的值保留为 bot 类的属性,并定义一个可以更改其值的方法。然后您可以将类或方法导出到 core.js 并从那里进行更改。
【解决方案2】:

感谢 djfdev 的评论,它可以正常工作, 我正在导出一个改变 restared 值的函数 我在我的 core.js 中导入该值

//bot.js
module.exports= {
    changerestarted: function() {
            restarted = true
    }
}

//core.js
const main = require("../../bot.js")
const auth = require("../../auth/auth.json")
module.exports = { 
    restart: function (message, bot) {
        if (message.author.id == 141218912934166528 || message.author.id == 533665091468656650) {
            console.log(message.author.tag + ' restarted The bot')
            message.reply('You restarted the bot, wait a few seconds')
            bot.channels.get("593824605144088586").send(message.author.tag + ' restarted the bot')
            bot.channels.get("593824605144088586").send('---------------------------------------------------')
            main.changerestarted()
            bot.channels.get("593824605144088586").send('Restarting...')
                .then(msg => bot.destroy())
                .then(() => bot.login(auth.token));
        }
        else {
            message.reply('I´m sorry,:no_entry_sign: you don´t have the permssion to run this command :no_entry_sign:')
            console.log(message.author.tag + ' tried to use -restart')
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多