index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const pump = require('pump');
  3. const bufferStream = require('./buffer-stream');
  4. class MaxBufferError extends Error {
  5. constructor() {
  6. super('maxBuffer exceeded');
  7. this.name = 'MaxBufferError';
  8. }
  9. }
  10. function getStream(inputStream, options) {
  11. if (!inputStream) {
  12. return Promise.reject(new Error('Expected a stream'));
  13. }
  14. options = Object.assign({maxBuffer: Infinity}, options);
  15. const {maxBuffer} = options;
  16. let stream;
  17. return new Promise((resolve, reject) => {
  18. const rejectPromise = error => {
  19. if (error) { // A null check
  20. error.bufferedData = stream.getBufferedValue();
  21. }
  22. reject(error);
  23. };
  24. stream = pump(inputStream, bufferStream(options), error => {
  25. if (error) {
  26. rejectPromise(error);
  27. return;
  28. }
  29. resolve();
  30. });
  31. stream.on('data', () => {
  32. if (stream.getBufferedLength() > maxBuffer) {
  33. rejectPromise(new MaxBufferError());
  34. }
  35. });
  36. }).then(() => stream.getBufferedValue());
  37. }
  38. module.exports = getStream;
  39. module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'}));
  40. module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true}));
  41. module.exports.MaxBufferError = MaxBufferError;