node.js - 无法访问我的 JSON 文件中的对象/字典元素?节点.js
问题描述
我正在创建一个不和谐的机器人,我需要在 JSON 文件中存储一个用户列表(以及他们想要的每个 YT 链接)。然后,当用户%users
输入 discord 时,机器人会返回所有用户及其 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. ");
}
解决方案
由于readFile
回调 -文档:
fs.readFile(file, (err, data) => {
if (err) throw err;
var YT = data["Video"];
var FinalUserID = data["ID"];
msg.channel.send("ID:" + FinalUserID + ", Link: " + YT);
});
推荐阅读
- javascript - 尝试在提交表单时附加到 URL
- node.js - 使用 express-validator 从端点验证 Id
- aws-lambda - 无法在 AWS Secrets Manager 上设置权限
- java - 将 CSS 样式设置为 JavaFX 中的特定元素
- symfony - 如何在 symfony phpunit kernelTestCase 中正确注入 monolog.logger / LoggerInterface 作为模拟
- python - 合并DataFrame中的行?
- css - 如何在离子中制作垂直范围滑块
- c++ - “使用”父类构造函数和在 C++ 中创建一个新的构造函数有什么区别?
- nhibernate - NHibernate 短路延迟加载从缓存中拉取
- sql-server - 调用 o898.save 时出错。Azure Synapse Analytics 连接器代码中遇到异常