Front end of the Slack clone application.

buffer-stream.js 847B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const PassThrough = require('stream').PassThrough;
  3. module.exports = opts => {
  4. opts = Object.assign({}, opts);
  5. const array = opts.array;
  6. let encoding = opts.encoding;
  7. const buffer = encoding === 'buffer';
  8. let objectMode = false;
  9. if (array) {
  10. objectMode = !(encoding || buffer);
  11. } else {
  12. encoding = encoding || 'utf8';
  13. }
  14. if (buffer) {
  15. encoding = null;
  16. }
  17. let len = 0;
  18. const ret = [];
  19. const stream = new PassThrough({objectMode});
  20. if (encoding) {
  21. stream.setEncoding(encoding);
  22. }
  23. stream.on('data', chunk => {
  24. ret.push(chunk);
  25. if (objectMode) {
  26. len = ret.length;
  27. } else {
  28. len += chunk.length;
  29. }
  30. });
  31. stream.getBufferedValue = () => {
  32. if (array) {
  33. return ret;
  34. }
  35. return buffer ? Buffer.concat(ret, len) : ret.join('');
  36. };
  37. stream.getBufferedLength = () => len;
  38. return stream;
  39. };