No Description

buffer-stream.js 894B

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