How would I limit upload speed from the server in node.js?

后端 未结 3 1978
清酒与你
清酒与你 2020-12-24 10:14

How would I limit upload speed from the server in node.js?

Is this even an option?

Scenario: I\'m writing some methods to allow users to automated-ly upload

相关标签:
3条回答
  • 2020-12-24 10:38

    Use throttle module to control the pipe stream speed

    npm install throttle

    var Throttle = require('throttle');
    
    // create a "Throttle" instance that reads at 1 b/s 
    var throttle = new Throttle(1);
    
    req.pipe(throttle).pipe(gzip).pipe(res);
    
    0 讨论(0)
  • 2020-12-24 10:51

    I do not think you can force a client to stream at a predefined speed, however you can control the "average speed" of the entire process.

    var startTime  = Date.now(),
        totalBytes = ..., //NOTE: you need the client to give you the total amount of incoming bytes
        curBytes   = 0;
    
    stream.on('data', function(chunk) { //NOTE: chunk is expected to be a buffer, if string look for different ways to get bytes written
         curBytes += chunk.length;
         var offsetTime = calcReqDelay(targetUploadSpeed);
         if (offsetTime > 0) {
             stream.pause();
             setTimeout(offsetTime, stream.resume);
         }
    });
    
    function calcReqDelay(targetUploadSpeed) { //speed in bytes per second
        var timePassed = Date.now() - startTime;
        var targetBytes = targetUploadSpeed * timePassed / 1000;
        //calculate how long to wait (return minus in case we actually should be faster)
        return waitTime;
    }
    

    This is of course pseudo code, but you probably get the point. There may be another, and better, way which I do not know about. In such case, I hope someone else will point it out.

    Note that it is also not very precise, and you may want to have a different metric than the average speed.

    0 讨论(0)
  • 2020-12-24 10:58

    Instead of rolling your own, the normal way to do this in production, is to let your load balancer or entry server throttle the incoming requests. See http://en.wikipedia.org/wiki/Bandwidth_throttling. It's not typically something an application needs to handle itself.

    0 讨论(0)
提交回复
热议问题