javascript - Node ,从 JSON 文件读取返回一个空数组

标签 javascript json node.js

function readTextFile(filename, callback){
    var fs = require('fs');
    fs.readFile(filename, 'utf8', function(err, data){
        if(err){
            throw err;
        }else{
            callback(data);
        }
    });
}

var set1 = [];
var set2 = [];
var set3 = [];
var set4 = [];
var set5 = [];

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;
});
console.log(set1);

运行这部分代码,使用“node jsonRead.js”为在 console.log() 中调用的任何数组返回 []。这段代码过去大约 80% 的时间都可以工作,但现在它根本不起作用,我不确定为什么。我将不胜感激关于如何让它再次工作的任何建议。

最佳答案

也许读取过程还在继续。

在回调中尝试 console.log(set1);:

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;

    console.log(set1);
});

这是因为 readTextFile 的回调函数在读取完成时执行,而其他代码则按写入执行。

您可以使用 Promises 来解决这个问题。查看 q 库,例如:https://github.com/kriskowal/q

关于javascript - Node ,从 JSON 文件读取返回一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328283/

相关文章:

javascript - 无法读取未定义的属性 'auth'

javascript - 在 jQuery 中使用 getJSON 函数时,回调函数不起作用

json - 将 JSON 解包为平面格式

javascript - iOS 原生应用,与 Cordova 2.9.0 集成

javascript - php 脚本中 json 返回值的 ajax jquery 错误

node.js - 由于 js 错误过多,Gulp.js 无法编译 angular.js 项目?

javascript - 如何验证两个加拿大邮政编码之间的距离

javascript - 机器人必须重新启动才能将用户输入传递给请求功能

javascript - 如何使用 Angular 1.5 和 Typescript 在组件 Controller 中获取绑定(bind)值?

javascript - 从浏览器打开我的 Electron 应用程序时如何获取输入