node.js - 不和谐.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);```
解决方案
好的,您要做的是在与当前文件相同的位置创建另一个文件。注意:仅为简化起见,您当然可以在所需的位置创建文件,但是您需要更改它的相对路径
我们现在将调用该文件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,那么它应该在你编写代码时自动完成,如果有问题,它也会让你知道
推荐阅读
- sql - 带有 if-else 逻辑的 SQL 查询
- arrays - Swift 5 - 显示带有对象数组的嵌套 JSON
- react-native - 导入其他文件时出现反应本机错误
- python - Python 中的一切都是对象,并且每个对象都实现为字典,这是真的吗?甚至是内置类型?
- firebase - Fetch collection startAfter documentID
- c# - 如何在 asp.net mvc 中显示数据库记录?
- python - AttributeError:“CalibratedClassifierCV”对象没有属性“coef_”
- mysql - MySQL COUNT() 还是 SUM()?
- java - Jhipster 返回 org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期:1
- javascript - 用PHP连接MySQL却通过JS查询MySQL?