【发布时间】:2020-10-23 00:48:25
【问题描述】:
我正在创建一个不和谐的机器人,我需要在 JSON 文件中存储一个用户列表(以及他们想要的每个 YT 链接)。然后,当用户在 discord 中键入 %users 时,机器人会返回所有用户及其 YT 链接。这些存储为字典它会通过查找文件夹中有多少个 json 文件(“./JSON”)并循环浏览每个文件并获取用户 ID 和链接来做到这一点。但是,当我使用fs.readFile 读取文件并尝试获取字典的相关元素(var YT = data["Video"];)时,遇到错误:Can't read property of 'Video' undefined.
这是出错的代码:
fs.readFile(file, (data) => {
var YT = data["Video"];
var FinalUserID = data["ID"];
msg.channel.send("ID:" + FinalUserID + ", Link: " + YT);
});
这里是主要块,以获得更多上下文:
if(msg.content.startsWith(prefix + "users"))
{
//finds how many files are in the directory JSON.
const fs = require('fs');
const dir = './JSON';
fs.readdir(dir, (err, files) => {
var filesJSON = files.length;
if(filesJSON == 0)
{
msg.channel.send("No users have been added.");
console.log("User did %users and no users were printed. ");
}
else if(filesJSON > 0)
{
const path = require('path');
//joining path of directory
const DirPath = path.join(__dirname, 'JSON');
//passing DirPath and callback function.
fs.readdir(DirPath, function(err, files) {
//Error catching/handling:
if(err)
{
return console.log('Unable to scan directory: ' + err);
return msg.channel.send('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function(file) {
//fetching the actual contents of each file:
fs.readFile(file, (data) => {
var YT = data["Video"];
var FinalUserID = data["ID"];
msg.channel.send("ID:" + FinalUserID + ", Link: " + YT);
});
});
});
console.log("User did %users and the users in 'users' array was printed. ");
}
【问题讨论】:
标签: node.js json discord.js