Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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;