gpt4 book ai didi

performance - 我将如何限制 node.js 中服务器的上传速度?

转载 作者:IT老高 更新时间:2023-10-28 23:07:17 26 4
gpt4 key购买 nike

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

这甚至是一种选择吗?

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

最佳答案

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

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;
}

这当然是伪代码,但您可能明白这一点。可能还有另一种更好的方法,我不知道。在这种情况下,我希望其他人指出。

请注意,它也不是很精确,您可能希望使用与平均速度不同的指标。

关于performance - 我将如何限制 node.js 中服务器的上传速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com