簡體   English   中英

如何在 js 中全局使用變量(跨多個文件)?

[英]How can I use a variable globally in js (across many files)?

我有以下問題:我正在使用 discord.js 編寫一個機器人,我是 JavaScript 的新手。我想要 2 個變量,為每個變量提供一個占位符值,然后更改一個命令文件中的值,並且能夠讀取不同命令文件中的值。 基本上,我希望能夠在許多不同的 JavaScript 文件中聲明變量、更改和讀取它們的值。 我的代碼在下面!

索引.js

const fs = require("fs");
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");

const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

let target;
let targetName;
global.target;
global.targetName;

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once("ready", () => {
    console.log("Ready!");
});

client.on("message", message => {
    console.log(`<${message.author.tag}> ${message.content}`);
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    try {
        target, targetName = client.commands.get(command).execute(message, args, target, targetName);
    }
    catch (error) {
        console.error(error);
        message.reply("there was an error trying to execute that command!");
    }

});

client.login(token);

目標.js

module.exports = {
    name: "target",
    description: "Targets the user(s) that the operator wants to trigger.",
    // execute(message, args) {
    execute(message, target, targetName) {
        if (message.member.roles.cache.has("737693607737163796") == true) {

            //  This will check if there are any users tagged. if not, the author will be targeted.
            if (!message.mentions.users.size) {
                message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${message.author.tag}sama*\n**__Armed and loaded, M-master__**`);
                target = (message.author.id);
                targetName = (message.author.tag);
                message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);
                return target, targetName;
            }

            // grab the "first" mentioned user from the message
            // this will return a `User` object, just like `message.author`
            const taggedUser = message.mentions.users.first();

            message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${taggedUser.tag}san*\n**__Armed and loaded, M-master`);
            target = (taggedUser.id);
            targetName = (taggedUser.tag);
            message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);

            console.log(`Target has changed! New target ID: ${target} New target name: ${targetName}`);
            return(target, targetName);
        }
        else {
            console.log("User isn't admin or there was an error executing the command!");
            message.reply("You don't have OP permissions! Only users with OP permissions are allowed to execute that command!");
        }
    },
};

targetCheck.js

module.exports = {
    name: "targetcheck",
    description: "Check for the current target!",
    // execute(message, args) {
    execute(message, target, targetName) {
        message.reply(`The current target is: ${targetName}(${target})`);
    },
};

由於您使用的是NodeJS ,因此您應該使用global object

在你設置的一個文件中

global.someAttributeName = "some value"

現在可以從任何地方訪問它

console.log(global.someAttributeName)
// logs : some value

您可以在帶有 JS 的項目中將庫用作 redux 以獲得全局狀態: https://redux.js.org/我認為您也可以使用全局 Node.js https://nodejs.org/api/globals.html#globals_global

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM