【发布时间】:2011-08-25 09:16:46
【问题描述】:
如何限制 node.js 中服务器的上传速度?
这甚至是一种选择吗?
场景:我正在编写一些方法来允许用户自动将文件上传到我的服务器。我想将上传速度限制为(例如)50kB/s(当然可以配置)。
【问题讨论】:
标签: performance file-upload upload node.js limit
如何限制 node.js 中服务器的上传速度?
这甚至是一种选择吗?
场景:我正在编写一些方法来允许用户自动将文件上传到我的服务器。我想将上传速度限制为(例如)50kB/s(当然可以配置)。
【问题讨论】:
标签: performance file-upload upload node.js limit
我不认为您可以强制客户端以预定义的速度进行流式传输,但是您可以控制整个过程的“平均速度”。
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;
}
这当然是伪代码,但您可能明白这一点。可能还有另一种更好的方法,我不知道。在这种情况下,我希望其他人指出。
请注意,它也不是很精确,您可能希望使用与平均速度不同的指标。
【讨论】:
在生产中执行此操作的正常方法是让负载平衡器或入口服务器限制传入请求,而不是自己滚动。见http://en.wikipedia.org/wiki/Bandwidth_throttling。这通常不是应用程序需要自己处理的事情。
【讨论】:
使用throttle模块控制管道流速度
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);
【讨论】: