readBuffer.js 969 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = readBuffer;
  6. function readBuffer(pipe, length, callback) {
  7. if (length === 0) {
  8. callback(null, Buffer.alloc(0));
  9. return;
  10. }
  11. let remainingLength = length;
  12. const buffers = [];
  13. const readChunk = () => {
  14. const onChunk = arg => {
  15. let chunk = arg;
  16. let overflow;
  17. if (chunk.length > remainingLength) {
  18. overflow = chunk.slice(remainingLength);
  19. chunk = chunk.slice(0, remainingLength);
  20. remainingLength = 0;
  21. } else {
  22. remainingLength -= chunk.length;
  23. }
  24. buffers.push(chunk);
  25. if (remainingLength === 0) {
  26. pipe.removeListener('data', onChunk);
  27. pipe.pause();
  28. if (overflow) {
  29. pipe.unshift(overflow);
  30. }
  31. callback(null, Buffer.concat(buffers, length));
  32. }
  33. };
  34. pipe.on('data', onChunk);
  35. pipe.resume();
  36. };
  37. readChunk();
  38. }