buffer-stream.js 847 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. };