Node.JS downloading hundreds of files simultaneously

久未见 提交于 2019-12-05 15:32:55

The solution is using async in this case.

Try it this way....with async.each()

var express = require('express');
var router = express.Router();
var fs = require('fs');
var youtubedl = require('youtube-dl');
var links = require('../models/Links');
var async = require('async')

router.get('/', function (req, res, next) {
    links.find({dlStatus: false}, function (err, docs) {

        if (err) {
            console.log(err);
            res.end();
        } else if (!docs) {
            console.log('No incomplete downloads!');
            res.end();
        } else {
            async.each(docs,function(doc,cb){
              var video = youtubedl(doc.url, [], {cwd: __dirname});

              // Will be called when the download starts.
              video.on('info', function (info) {
                  console.log('Download started');
                  console.log(info);
              });

              video.pipe(fs.createWriteStream('./downloads/' + docs.id + '-' + i + '.mp4'));
              video.on('complete', function complete(info) {
                  links.findOneAndUpdate({url: info.webpage_url}, {dlStatus: true}, function (err, doc) {
                      if (err){
                        console.log(err);
                        cb(err);
                      }
                      else {
                        console.log('Download completed!');
                        cb()
                      }
                  });
              });

            },function(err){
              if(err)
                return console.log(err);
              console.log("Every thing is done,Here!!");
            })
        }
    });
});

module.exports = router;

And you can process every thing in batch too using async.eachLimits().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!