节点,从JSON文件读取返回一个空的数组

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%的时间,但现在它根本不工作,我不知道为什么。 我将不胜感激关于如何让它再次运作的任何build议。

也许阅读过程仍在继续。

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

 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的callbackreadTextFile是在读完之后执行的,而其他的代码是按照写的执行的。

你可以通过使用Promise解决这个问题。 检出q库,例如: https : //github.com/kriskowal/q

执行代码的Node.js范例是Asynchronous,意思是调用asynchronous方法后执行下一行代码。 在你上面的例子中,readTextFile被调用,执行将继续到下一行。 它不会等待回报。