From 127d83cd70d0d1b33f3883186f181f15c7ed5c96 Mon Sep 17 00:00:00 2001 From: Greg Poole Date: Mon, 10 Aug 2020 07:00:53 +1000 Subject: [PATCH] Allow `maxBuffer` option to be set to Buffer `MAX_LENGTH` (#40) Co-authored-by: Sindre Sorhus --- index.js | 4 +++- test.js | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 340ea7d..71f3991 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ 'use strict'; +const {constants: BufferConstants} = require('buffer'); const pump = require('pump'); const bufferStream = require('./buffer-stream'); @@ -24,7 +25,8 @@ async function getStream(inputStream, options) { let stream; await new Promise((resolve, reject) => { const rejectPromise = error => { - if (error) { // A null check + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } diff --git a/test.js b/test.js index ccff3cf..0809a8a 100644 --- a/test.js +++ b/test.js @@ -1,4 +1,5 @@ import fs from 'fs'; +import {constants as BufferConstants} from 'buffer'; import {Readable as ReadableStream} from 'stream'; import test from 'ava'; import intoStream from 'into-stream'; @@ -70,6 +71,16 @@ test('maxBuffer throws a MaxBufferError', async t => { await t.throwsAsync(setup(['abcd'], {maxBuffer: 3}), getStream.MaxBufferError); }); +test('maxBuffer throws a MaxBufferError even if the stream is larger than Buffer MAX_LENGTH', async t => { + // Create a stream 1 byte larger than the maximum size a buffer is allowed to be + function * largeStream() { + yield Buffer.allocUnsafe(BufferConstants.MAX_LENGTH); + yield Buffer.allocUnsafe(1); + } + + await t.throwsAsync(setup(largeStream(), {maxBuffer: BufferConstants.MAX_LENGTH, encoding: 'buffer'}), /maxBuffer exceeded/); +}); + test('Promise rejects when input stream emits an error', async t => { const readable = new ReadableStream(); const data = 'invisible pink unicorn';