progress-stream icon indicating copy to clipboard operation
progress-stream copied to clipboard

Doesn't get the length of stream automatically using request.

Open vibhor1997a opened this issue 6 years ago • 1 comments

Given in the readme section

Gets the length of the stream automatically if you're using the request or http module. You can also pass the length on initiation. Progress-stream will also check to see if the stream already has a length property.

I tried this example in the readme and length was 0(default value) not the length of the stream.

var progress = require('progress-stream');
var req = require('request');
var fs = require('fs');

var str = progress({
    time: 1000
});

str.on('progress', function (progress) {
    console.log(Math.round(progress.percentage) + '%');
});

req('http://cachefly.cachefly.net/100mb.test', { headers: { 'user-agent': 'test' } })
    .pipe(str)
    .pipe(fs.createWriteStream('test.data'));

vibhor1997a avatar Mar 29 '18 05:03 vibhor1997a

@vibhor1997a , I solving this problem by adding a HEAD request before and set the length of the bar.

here is my code:

async function downloadVideoFromURL(url, fullPath) {
    function _getContentLength(url) {
        return new Promise((resolve, reject) => {
            request.head(url, {}, (err, res) => {
                if (err) reject(err)
                resolve(res.headers['content-length'])
            })
        })
    }
    const contentLength = await _getContentLength(url);
    const str = progress({ time: 1000, length: contentLength });

    str.on('progress', (progress) => {
        console.log(`downloading video from url: ${url}, ${Math.round(progress.percentage) + '%'}`);
    })
    return new Promise((resolve, _) => {
        request(url)
            .pipe(str)
            .pipe(fs.createWriteStream(fullPath))
            .on('close', resolve);
    });
}

Hatuw avatar Apr 16 '20 02:04 Hatuw