按计数下载图像

时间:2014-07-22 22:27:17

标签: javascript node.js asynchronous

我使用async在每个请求上下载uri并在达到计数时关闭,但是我发现我仍然遇到了文件未正确下载的相同问题并在它达到最大值之前退出解决此问题的最佳方法是什么?一如既往,感谢您的帮助。

async.each(images, function (image, callback) {
  var uri = image.attribs.src;
  var random = (Math.random() * (3 - 1) + 1) | 0;
  var stream = fs.createWriteStream(outFile);
  request(uri).pipe(stream);
  stream.on('finish', callback);
  console.log('[' + chalk.green('✓') + ']' + ' wrote image ' + count);
  count++;
  if (count === commander.max) {
    process.exit(0); 
  }
  sleep.sleep(random);
}, function (error) {
     if (error) {
       console.log('[' + chalk.red('×') + ']' + ' failed on image ' + count);
     }
});  

1 个答案:

答案 0 :(得分:1)

您实际上并没有等待每个请求完成,也没有调用回调。您需要侦听要发送到管道的可写流上的finish事件。因此,您希望代码看起来像这样:

async.each(images, function (image, callback) {
  var uri = image.attribs.src;
  var random = (Math.random() * (3 - 1) + 1) | 0;
    var writable = fs.createWriteStream(outFile);
    request(uri).pipe(writable);
    writable.on('finish', callback);
    console.log('[' + chalk.green('✓') + ']' + ' wrote image ' + count);
    count++;
    if (count === commander.max) {
      process.exit(0); 
    }
    sleep.sleep(random);
}, function (error) {
     if (error) {
       console.log('[' + chalk.red('×') + ']' + ' failed on image ' + count);
     }
});   

在此处查看更多信息:http://nodejs.org/api/stream.html#stream_event_finish