Front end of the Slack clone application.

index.js 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const bufferStream = require('./buffer-stream');
  3. function getStream(inputStream, opts) {
  4. if (!inputStream) {
  5. return Promise.reject(new Error('Expected a stream'));
  6. }
  7. opts = Object.assign({maxBuffer: Infinity}, opts);
  8. const maxBuffer = opts.maxBuffer;
  9. let stream;
  10. let clean;
  11. const p = new Promise((resolve, reject) => {
  12. const error = err => {
  13. if (err) { // null check
  14. err.bufferedData = stream.getBufferedValue();
  15. }
  16. reject(err);
  17. };
  18. stream = bufferStream(opts);
  19. inputStream.once('error', error);
  20. inputStream.pipe(stream);
  21. stream.on('data', () => {
  22. if (stream.getBufferedLength() > maxBuffer) {
  23. reject(new Error('maxBuffer exceeded'));
  24. }
  25. });
  26. stream.once('error', error);
  27. stream.on('end', resolve);
  28. clean = () => {
  29. // some streams doesn't implement the `stream.Readable` interface correctly
  30. if (inputStream.unpipe) {
  31. inputStream.unpipe(stream);
  32. }
  33. };
  34. });
  35. p.then(clean, clean);
  36. return p.then(() => stream.getBufferedValue());
  37. }
  38. module.exports = getStream;
  39. module.exports.buffer = (stream, opts) => getStream(stream, Object.assign({}, opts, {encoding: 'buffer'}));
  40. module.exports.array = (stream, opts) => getStream(stream, Object.assign({}, opts, {array: true}));