I'm playing with Node and have a strange problem (well, strange to me). It's been a long time since I did any Javascript, so the problem is likely staring me in the face.
I'm iterating through a list of JSON text files in a directory, parsing the text from each file. It moves through the directory correctly; when I check with console.log, each object appears correct.
However, when I attempt to push this onto an array, nothing happens, the size remains one at the end of the loop. It feels like a scope issue.
Thanks for any advice.
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);
});