I'm new to Node and trying to ensure that I'm using sane designs for a JSON-driven web app.
I've got a bunch of data stored in Redis and am retrieving it through node, streaming out the results as they come from Redis. Here's a good example of what I'm doing:
app.get("/facility", function(req, res) {
rc.keys("FACILITY*", function(err, replies) {
res.write("[");
replies.forEach(function (reply, i) {
rc.get(reply, function(err, reply) {
res.write(reply);
if (i == replies.length-1) {
res.write("]");
res.end();
}
else
res.write(",");
});
});
});
});
Essentially I'm getting set of keys from Redis and then requesting each one, streaming out the result into semi-manually created JSON (the strings coming out of Redis are already in JSON). Now this works nicely, but I can't help thinking that the i == replies.length-1 is a little untidy?
I could do all this with mget in Redis, but that isn't really the point I'm trying to get it; it's how best to handle async looping with forEach, streaming the output and gracefully closing off the connection with res.end with the looping is done.
Is this the best way, or is there a more elegant pattern I could follow?