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

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

这甚至是一个select?

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

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

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

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

请注意,它也不是很精确,您可能需要具有与平均速度不同的度量标准。

使用节stream阀模块来控制pipe道stream速

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

在生产环境中执行此操作的常规方法是让负载平衡器或入口服务器遏制传入的请求。 请参阅http://en.wikipedia.org/wiki/Bandwidth_throttling 。 这通常不是应用程序需要处理的东西。