有没有办法在 connect 或 express 中设置模式或值来模拟慢速文件上传?
问问题
1242 次
1 回答
2
First, install node-limiter
then create a Transform
stream that will throttle any Stream
s:
var util = require('util');
var Transform = require('stream').Transform;
var TokenBucket = require('limiter').TokenBucket;
function BucketStream(rate, interval, parentBucket, options) {
Transform.call(this, options);
this.bucket = new TokenBucket(Number.POSITIVE_INFINITY, rate, interval, parentBucket);
}
util.inherits(BucketStream, Transform);
BucketStream.prototype._transform = function(chunk, encoding, callback) {
this.bucket.removeTokens(chunk.length, function(err) {
callback(err, chunk);
});
};
Then the request is a ReadableStream
:
var bucketStream = new BucketStream(1024 * 500, 'second'); // 500KB/sec
req.pipe(bucketStream);
Now read from bucketStream
(instead from req) as fast as you want, you'll only get 500KB/sec
I did this on top of my head so beware :)
于 2014-08-25T14:35:55.650 回答