我将如何限制 node.js 中服务器的上传速度? [英] How would I limit upload speed from the server in node.js?
问题描述
如何限制 node.js 中服务器的上传速度?
How would I limit upload speed from the server in node.js?
这甚至是一种选择吗?
场景:我正在编写一些方法来允许用户自动将文件上传到我的服务器.我想将上传速度限制为(例如)50kB/s(当然可以配置).
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屋!