UNPKG

stream-size

Version:

Get the size of a stream and abort it if threshold is reached

21 lines 1.05 kB
import { Transform } from 'stream'; /** * @param maximumSizeInBytesAllowed Optional. Set this parameter to the maximum amount of bytes before throwing an error and closing the stream. Leave unset to allow any amount of bytes and not apply any limit. */ function getSizeTransform(maximumSizeInBytesAllowed) { const transformedStream = new Transform({ transform(chunk, encoding, callback) { const sizeInBytesAfterWritingChunk = this.sizeInBytes + Buffer.byteLength(chunk, encoding); if (maximumSizeInBytesAllowed && sizeInBytesAfterWritingChunk > maximumSizeInBytesAllowed) { return callback(new Error(`Stream exceeded maximum size of ${maximumSizeInBytesAllowed} bytes (${sizeInBytesAfterWritingChunk} bytes found).`)); } this.sizeInBytes = sizeInBytesAfterWritingChunk; callback(null, chunk); }, }); transformedStream.sizeInBytes = 0; return transformedStream; } export default getSizeTransform; //# sourceMappingURL=index.js.map