我在和Node玩,有一个奇怪的问题(对我来说很奇怪)。自从我做了Javascript以来,已经有很长的一段时间了,所以问题很可能在我面前凝视。Javascript(节点)将对象推入阵列
我遍历目录中的JSON文本文件列表,解析每个文件中的文本。它正确地移动目录;当我检查console.log时,每个对象显示正确。
但是,当我试图将它推到一个数组上时,没有任何反应,大小在循环结束时保持为1。这感觉就像一个范围问题。
感谢您的任何建议。
app.get("/people/:value1/metrics/:value2", function(req, res) {
var value1 = req.params.value1;
var value2 = req.params.value2;
var personPath = "people/" + value1 + "/" + value2;
var content;
var data = [];
fs.readdir(personPath, function(err, files) {
if(err) {
console.log(err);
}
files.forEach(function (file, index) {
content = fs.readFileSync(personPath + '/' + file);
console.log(JSON.parse(content)); //Correctly outputs the object.
content = JSON.parse(content);
data.push(content);
});
});
console.log(data.length); //Always 0.
res.send(data);
});
这看起来像异步代码,将您送入READDIR –
谢谢你的建议所有,这是伟大的。 –