首页 > 解决方案 > 无法访问我的 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. "); 
      }

标签: node.jsjsondiscord.js

解决方案


由于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);
});

推荐阅读