all files / blackbird/modules/utils/ bufferStream.js

95.45% Statements 21/22
75% Branches 6/8
100% Functions 4/4
95.45% Lines 21/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44           150×   150×       150× 150× 150×   150×   150× 169×   169×   166×       150× 150×     150× 150×          
const bodec = require("bodec");
const Promise = require("./Promise");
const MaxLengthExceededError = require("./MaxLengthExceededError");
const R = require("ramda");
 
/**
 * Returns a promise for a buffer of all content in the given stream up to
 * the given maximum length.
 */
function bufferStream(stream, maxLength) {
    maxLength = maxLength || Infinity;
 
    Iif (!stream.readable) {
        throw new Error("Cannot buffer stream that is not readable");
    }
 
    return new Promise(function (resolve, reject) {
        const chunks = [];
        let length = 0;
 
        stream.on("error", reject);
 
        stream.on("data", function (chunk) {
            length += chunk.length;
 
            if (length > maxLength) {
                reject(new MaxLengthExceededError(maxLength));
            } else {
                chunks.push(chunk);
            }
        });
 
        stream.on("end", function () {
            resolve(bodec.join(chunks));
        });
 
        Eif (R.is(Function, stream.resume)) {
            stream.resume();
        }
    });
}
 
module.exports = bufferStream;