【问题标题】:Can't access element of object/dictionary in my JSON file? Node.js无法访问我的 JSON 文件中的对象/字典元素?节点.js
【发布时间】: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


    【解决方案1】:

    因为readFile回调-docs

    fs.readFile(file, (err, data) => {
      if (err) throw err;
      var YT = data["Video"];
      var FinalUserID = data["ID"];
      msg.channel.send("ID:" + FinalUserID + ", Link: " + YT);
    });
    

    【讨论】:

    • 然后我得到错误:对目录的非法操作
    • 这个错误与原始问题有关吗?无论如何,请确保您没有读取带有fs 的目录。
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2023-03-22
    • 2021-06-28
    • 2021-09-27
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多