簡體   English   中英

如何在Node.js中一一下載文件?

[英]How to download files one by one in node js?

我正在嘗試使用請求庫下載多個文件,我需要一個一個地下載它們,並顯示一個進度欄,文件鏈接存儲在一個數組中,該數組將它們傳遞給函數以開始下載

const request = require('request')
const fs = require('fs')
const ProgressBar = require('progress')

async function downloadFiles(links) {
    for (let link of links) {
        let file = request(link)
        file.on('response', (res) => {
            var len = parseInt(res.headers['content-length'], 10);
            console.log();
            bar = new ProgressBar('  Downloading [:bar] :rate/bps :percent :etas', {
                complete: '=',
                incomplete: ' ',
                width: 20,
                total: len
            });
            file.on('data', (chunk) => {
                bar.tick(chunk.length);
            })
            file.on('end', () => {
                console.log('\n');
            })
        })
        file.pipe(fs.createWriteStream('./downloads/' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)))
    }
}


let links = ['https://speed.hetzner.de/100MB.bin', 'https://speed.hetzner.de/100MB.bin', 'https://speed.hetzner.de/100MB.bin', 'https://speed.hetzner.de/100MB.bin']
downloadFiles(links)

到目前為止,這就是我所得到的,問題是請求是異步的,我嘗試使用async / await,但是那樣我無法使進度條正常工作。 如何使文件一次被下載並具有進度欄?

根據我對async.queue評論,這就是我要寫的方式。 您可以根據需要dl.downloadFiles([])調用dl.downloadFiles([]) ,它只會一次又一次地提取添加到隊列中的所有內容。

const request = require('request')
const async = require('async')
const fs = require('fs')
const ProgressBar = require('progress')

class Downloader {
    constructor() {
        this.q = async.queue(this.singleFile, 1);

        // assign a callback
        this.q.drain(function() {
            console.log('all items have been processed');
        });

        // assign an error callback
        this.q.error(function(err, task) {
            console.error('task experienced an error', task);
        });
    }

    downloadFiles(links) {
        for (let link of links) {
            this.q.push(link);
        }
    }

    singleFile(link, cb) {
        let file = request(link);
        let bar;
        file.on('response', (res) => {
            const len = parseInt(res.headers['content-length'], 10);
            console.log();
            bar = new ProgressBar('  Downloading [:bar] :rate/bps :percent :etas', {
                complete: '=',
                incomplete: ' ',
                width: 20,
                total: len
            });
            file.on('data', (chunk) => {
                bar.tick(chunk.length);
            })
            file.on('end', () => {
                console.log('\n');
                cb();
            })
        })
        file.pipe(fs.createWriteStream('./downloads/' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)))
    }
}

const dl = new Downloader();

dl.downloadFiles([
    'https://speed.hetzner.de/100MB.bin',
    'https://speed.hetzner.de/100MB.bin'
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM