const { Transform } = require('stream'); /** * Throttle stream to a specific bytes-per-second limit */ class ThrottleStream extends Transform { /** * @param {number} bytesPerSecond Limit rate */ constructor(bytesPerSecond) { super(); this.bytesPerSecond = bytesPerSecond; this.startTime = Date.now(); this.bytesWritten = 0; } _transform(chunk, encoding, callback) { this.bytesWritten += chunk.length; this.push(chunk); if (!this.bytesPerSecond || this.bytesPerSecond <= 0) { return callback(); } const elapsedMs = Date.now() - this.startTime; const expectedMs = (this.bytesWritten / this.bytesPerSecond) * 1000; const sleepMs = expectedMs - elapsedMs; if (sleepMs > 0) { setTimeout(callback, sleepMs); } else { callback(); } } } /** * Helper to wrap any standard readable stream in a dynamic speed throttle * @param {import('fs').ReadStream} readStream * @param {number} speedMbps Throttle target in Megabits per second (e.g. 2 Mbps) * @returns {Transform} Throttled stream */ function throttleStream(readStream, speedMbps) { const bytesPerSecond = (speedMbps * 1000000) / 8; const throttle = new ThrottleStream(bytesPerSecond); return readStream.pipe(throttle); } module.exports = { ThrottleStream, throttleStream };