aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

How to readstream multiple files #18

Closed toddhickerson closed 11 years ago

toddhickerson commented 11 years ago

Do you have any examples on how to read/send multiple files in the same response? The input seems to only take one id not an array.

ediazal commented 11 years ago

I don't know if it's the best solution, but try something like this.

var _=require('underscore')
// files is the array of filenames you want to read
function(files, cb){ 
  var gfs = Grid(your_db_here);
  gfs.files.find({filename:{$in:files}).toArray(function(err, files){
    if (err) {return cb (err);}
    var done=0
    _.each(files, function(e, i, l){
      var readstream = gfs.createReadStream({_id:e._id});  
      readstream.pipe(Your_write_stream_here);
      readstream.on('end',function(){
        if (++done==files.length){
          return cb (null);    
        }
      });
    });
  });
}