title: Using NodeJS and async.queue to download and save lots of images to local disk
body: <p>OK I have a NodeJS app and I'm trying to download lots of images from a web server (about 500 for now but the number will increase). The problem I get is a "Unhandled stream error in pipe Error: EMFILE" because it seems that too much files get opened at the same time.</p>
  
  <p>So I'm trying to use async.queue to process files by batches of 20. But I still get the error. </p>
  
  <pre><code>SomeModel.find({}, function(err, photos){
      if (err) {
          console.log(err);
      }
      else {
  
          photos.forEach(function(photo){
  
              var url = photo.PhotoURL;
              var image = url.replace('http://someurl.com/media.ashx?id=', '').replace('&amp;otherstuffattheend', '.jpg');
              photo.target = image;
  
              var q = async.queue(function (task) {
                  request
                      .get(task.PhotoURL)
                      .on('response', function(response) {
                          console.log(task.PhotoURL + ' : ' + response.statusCode, response.headers['content-type']);
                          console.log(task.target);
                      })
                      .on('error', function(err) {
                          console.log(err);
                      })
                      .pipe(fs.createWriteStream(task.target));
              }, 20);
  
              q.push(photo, function(err) {
                  if (err) {
                      console.log(err);
                  }
              });
  
              q.drain = function() {
                  console.log('Done.')
              }
  
          });
      }
  });
  </code></pre>
  
  <p>What am I doing wrong ? Many thanks for your time and help.</p>