You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
841 B

4 years ago
  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. };