JavaScript变量未在函数外部更新

时间:2020-03-07 06:31:48

标签: javascript node.js json

我目前正在Glitch上为twitch.tv聊天机器人编写应用程序,但无法访问位于单独json文件中的数据。我的过程如下:

因此,起初,我在将本地json文件加载到javascript文件时遇到了麻烦。直到我在线找到以下代码:

const fs = require('fs')
let jsonData = {}
fs.readFile('file.json', 'utf-8', (err, data) => {
  if (err) throw err;

  jsonData = JSON.parse(data)
})

然后我在方括号内添加了console.log,以查看它是否正确读取了文件。效果很好。

目前,我无法让jsonData超出括号,无法用于我的应用程序的其他部分。我进行了一些谷歌搜索,发现可能必须调用该函数才能在外部使用它。 (很抱歉,如果这没有意义,我是javascript的新手,不确定使用的正确术语)。因此,我设置了一些测试console.log调用,以查看其工作原理。

这是文件阅读器部分的当前代码:

//----------------------------------------------------------------------------------------------------//
// reading json file
//----------------------------------------------------------------------------------------------------//
let jsonData = {};
function fileGet() {
  fs.readFile("testquotes.json", "utf-8", (err, data) => {
    if (err) throw err;
    jsonData = JSON.parse(data);
    console.log("inside function");
    console.log(jsonData);
    return jsonData;
  });
}
console.log("outside function: Before call");
console.log(jsonData);
fileGet();
console.log("outside function:After call");
console.log(jsonData);

这是控制台中的输出

outside function: Before call
{}
outside function:After call
{}
inside function
{ Quotes:
   [ [ [Array], [Array], [Array] ], [ 'Zilean', 'Zoe', 'Zyra' ] ] }

因此,正在正确地从文件中读取数据。

关于我需要的东西

//----------------------------------------------------------------------------------------------------//
// This simple bot will simply monitor chat logging for instances of '!twitter' or '!github'.
//----------------------------------------------------------------------------------------------------//
client.on("chat", (channel, user, message, self) => {
  switch (message) {
    case "!hello":
      client.action(channellist[0], `hi! im a work in progess`);
      break;
    case "!test":
      client.action(
        channellist[0],
        `${user["display-name"]} uwu ?? thanks for testing me out`
      );
      break;
// gives chat the quote to guess
    case "!quote":
      client.action(
        channellist[0],
        `${user["display-name"]} owo ?? jsonData[0][0][0]`
      ); 
      break;
    default:
      break;
  }
});

老实说,我已经尝试使用Google搜寻和其他随机项目,但不确定下一步该怎么做。不好意思,如果这不是一个好问题。不应重复。任何帮助都将不胜感激!

0 个答案:

没有答案