如何限制node.js中服务器的上传速度? [英] How would I limit upload speed from the server in node.js?

查看:1026
本文介绍了如何限制node.js中服务器的上传速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制node.js服务器的上传速度?



这甚至是一个选项吗?



场景:我正在编写一些方法来允许用户自动将文件上传到我的服务器。我想限制上传速度(例如)50kB / s(当然配置)。

解决方案

我不认为您可以强制客户端以预定义的速度进行流式处理,但是您可以控制整个流程的平均速度。

  var startTime = Date.now(),
totalBytes = ...,//注意:你需要客户端给你传入字节总数
curBytes = 0;

stream.on('data',function(chunk){//注意:chunk应该是一个缓冲区,如果字符串寻找不同的方法来获取写入的字节
curBytes + = chunk.length;
var offsetTime = calcReqDelay(targetUploadSpeed);
if(offsetTime> 0){
stream.pause();
setTimeout(offsetTime,stream.resume) ;
}
});

函数calcReqDelay(targetUploadSpeed){//速度以字节为单位
var timePassed = Date.now() - startTime;
var targetBytes = targetUploadSpeed * timePassed / 1000;
//计算需要等待多久(返回减去以防我们实际上应该更快)
return waitTime;



$ b $ p
$ b

这当然是伪代码,但你可能会明白这一点。可能有另外一种更好的方式,我不知道。在这种情况下,我希望别人会指出。



请注意,它也不是很精确,你可能想要有一个不同的指标比平均速度。


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 files to my server. I want to limit the upload speed to (for instance) 50kB/s (configurable of course).

解决方案

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.

这篇关于如何限制node.js中服务器的上传速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆