buffer-stream.js 841 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const {PassThrough} = require('stream');
  3. module.exports = options => {
  4. options = Object.assign({}, options);
  5. const {array} = options;
  6. let {encoding} = options;
  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. };