首页 > 解决方案 > 不和谐.js | 有没有办法将变量存储到不同的 js 文件中?

问题描述

所以我正在制作一个 DS 机器人,它将每隔一小时将我提供给机器人的随机链接/图像发送到聊天中。我有很多链接/图片,在主要 index.js 上真是一团糟

有没有办法将另一个 js 文件中的变量带到我的主文件中?

这是我的代码:

const app = express();
const port = 3000;

app.get('/', (req, res) => res.send('Hello Foxi!'));

app.listen(port, () => console.log(`The Dealer is listening at http://localhost:${port}`));

// ====================The Dealer's Heart====================

const Discord = require('discord.js');
const client = new Discord.Client();

// 804488904634925076
//var bbChannel = client.channels.cache.get('809808576406093847');

//console.log(`Logged in as ${client.user.tag}!`);

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
  setInterval(() => {
    var bbChannel = client.channels.cache.get('804488904634925076');
    const image = images[Math.floor(Math.random() * images.length)];
    const random = new Discord.MessageEmbed()
      .setTitle('HOURLY PICTURES')
      .setAuthor('Brought to you by: The Dealer')
      .setDescription('SOME IMAGES MAY REPEAT')
      .setImage(image)
    bbChannel.send(random)
  }, 3600000);
});


client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong!');
  } 
});

//Images
var images =["Image1", "Image2", "Image3", "ETC"];

client.login(process.env.DISCORD_TOKEN);``` 

标签: node.js

解决方案


好的,您要做的是在与当前文件相同的位置创建另一个文件。注意:仅为简化起见,您当然可以在所需的位置创建文件,但是您需要更改它的相对路径

我们现在将调用该文件images.json。在该文件中,您使用一个简单的 JSON 结构,并且基本上将您在文件底部的数组放在此处。

{
    "images": [
        "link1",
        "link2",
        "link3"
    ]
}

现在您所要做的就是将它导入到您的主文件中。你这样做就像你对其他任何事情一样。我们在这里使用解构来只提取我们想要的值。注意:如果您有多个要访问的条目,您也可以导入整个文件。在一定数量之后,这通常是要走的路,因为它没有那么多工作。程序员是一群相当懒惰的人

const { images } = require('./images.json');
// if you want the entire thing you do this
// const images = require('./images.json');
// and then to access the array
// console.log(images.images);

如果您使用解构,那么您根本不需要更改代码,因为您已经根据需要定义了变量。如果您不这样做,请使用上述方法。

显然,您现在可以删除代码底部的数组。

另一个注意事项:如果你使用了一个中规中矩的 IDE,那么它应该在你编写代码时自动完成,如果有问题,它也会让你知道


推荐阅读