简体   繁体   中英

Node.js image download with bandwidth limit

I'm currently testing out something at the reddit image download feature of my discord bot. The code below is just a scaffold for testing. I was wondering if there is a way of capping or throttling the bandwidth of an image download from a request response. The image is just downloaded once.

I already used different request modules from npm like superagent and their plugins but none of them worked. I also found the module ratelimit but this is very old (last commit 2012) and only supports http-requests (no https).

var request = require('request')
var fs = require('fs')

request('https://upload.wikimedia.org/wikipedia/commons/6/60/Eol.jsc.nasa.gov_ESC_large_ISS005_ISS005-E-16279.JPG')
    .on('response', (response) => {
        // limitBandwidth()
    })
    .on('data', (data) => {
        
    })
    .pipe(fs.createWriteStream('test.jpg'))

It works with the module throttle . You just have to pass in the throttle in front of the actual createWriteStream-pipe.

var request = require('request')
var fs = require('fs')
var Throttle = require('throttle');


var throttle = new Throttle(1024 * 1024 / 2)

request('https://upload.wikimedia.org/wikipedia/commons/6/60/Eol.jsc.nasa.gov_ESC_large_ISS005_ISS005-E-16279.JPG')
    .on('response', (response) => {
        
    })
    .on('data', (data) => {
        
    })
    .pipe(throttle).pipe(fs.createWriteStream('test.jpg'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM