index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. const {constants: BufferConstants} = require('buffer');
  3. const pump = require('pump');
  4. const bufferStream = require('./buffer-stream');
  5. class MaxBufferError extends Error {
  6. constructor() {
  7. super('maxBuffer exceeded');
  8. this.name = 'MaxBufferError';
  9. }
  10. }
  11. async function getStream(inputStream, options) {
  12. if (!inputStream) {
  13. return Promise.reject(new Error('Expected a stream'));
  14. }
  15. options = {
  16. maxBuffer: Infinity,
  17. ...options
  18. };
  19. const {maxBuffer} = options;
  20. let stream;
  21. await new Promise((resolve, reject) => {
  22. const rejectPromise = error => {
  23. // Don't retrieve an oversized buffer.
  24. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
  25. error.bufferedData = stream.getBufferedValue();
  26. }
  27. reject(error);
  28. };
  29. stream = pump(inputStream, bufferStream(options), error => {
  30. if (error) {
  31. rejectPromise(error);
  32. return;
  33. }
  34. resolve();
  35. });
  36. stream.on('data', () => {
  37. if (stream.getBufferedLength() > maxBuffer) {
  38. rejectPromise(new MaxBufferError());
  39. }
  40. });
  41. });
  42. return stream.getBufferedValue();
  43. }
  44. module.exports = getStream;
  45. // TODO: Remove this for the next major release
  46. module.exports.default = getStream;
  47. module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
  48. module.exports.array = (stream, options) => getStream(stream, {...options, array: true});
  49. module.exports.MaxBufferError = MaxBufferError;