Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查JSON文件是否存在,然后需要它_Javascript_Json_Node.js - Fatal编程技术网

Javascript 检查JSON文件是否存在,然后需要它

Javascript 检查JSON文件是否存在,然后需要它,javascript,json,node.js,Javascript,Json,Node.js,我想检查JSON文件是否存在,然后需要它,如果不存在,就创建它。这已经完成了,但是当在代码中使用jsonfile时,我得到了`ReferenceError:config未定义 代码: 在使用JSON文件之前,我如何检查它是否存在,而不会导致错误?您可以使用try-catch try { const cleverbot = require("cleverbot.io"), clever = new cleverbot(config.cleverbotUser, config.cleverBotT

我想检查JSON文件是否存在,然后需要它,如果不存在,就创建它。这已经完成了,但是当在代码中使用jsonfile时,我得到了`ReferenceError:config未定义

代码:


在使用JSON文件之前,我如何检查它是否存在,而不会导致错误?

您可以使用try-catch

try
{
const cleverbot = require("cleverbot.io"), 
clever = new cleverbot(config.cleverbotUser, config.cleverBotToken);
require('fs').exists("config.json", function(exists) {
if (exists) {
     fs.readFile("config.json", (err, data) => {
     if (err) {
        console.log("Config file doesnot exist, creationg one.");

    //Default config values
    let obj = {
        cleverbotUser: "TOKEN",
        cleverBotToken: "TOKEN"
    };

    jsonfile.spaces = 4;
    jsonfile.writeFile("config.json", obj, (err) => {
        console.log(err)
    })
} else {
    global.config = require("./config.json");
}
});
}
});
 }
catch (e) {
if (e instanceof Error && e.code === "MODULE_NOT_FOUND")
    console.log("Can't load foo!");
else
    throw e;
}

try-catch将处理加载模块中的错误,文件exists将处理json文件,以查看是否找到了它

config not defined是关于第二行中使用的config对象的

 clever = new cleverbot(config.cleverbotUser, config.cleverBotToken);

它肯定没有定义,您可能忘记了需要它。

我认为您应该首先定义配置变量。它可以是空的,也可以填充一些默认数据

const config = {
   cleverbotUser: "", 
   cleverBotToken: ""
}

然后尝试从文件加载值,最后初始化
cleverbot
对象。此方法的唯一条件是您的类可以使用这些参数运行,如果不是,您应该使用
try catch
块并抛出异常。

这只是掩盖问题,而不是解决问题。您在哪里定义第2行中使用的var
config
const config = {
   cleverbotUser: "", 
   cleverBotToken: ""
}