streams.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // @ts-check
  2. /**
  3. * Promises are promises and streams are streams, and ne'er the twain shall
  4. * meet.
  5. * @module
  6. */
  7. 'use strict'
  8. const { pipeline } = require('node:stream/promises')
  9. const zlib = require('node:zlib')
  10. const { WritableBuffer } = require('@overleaf/stream-utils')
  11. /**
  12. * Create a promise for the result of reading a stream to a buffer.
  13. *
  14. * @param {import('node:stream').Readable} readStream
  15. * @return {Promise<Buffer>}
  16. */
  17. async function readStreamToBuffer(readStream) {
  18. const bufferStream = new WritableBuffer()
  19. await pipeline(readStream, bufferStream)
  20. return bufferStream.contents()
  21. }
  22. exports.readStreamToBuffer = readStreamToBuffer
  23. /**
  24. * Create a promise for the result of un-gzipping a stream to a buffer.
  25. *
  26. * @param {NodeJS.ReadableStream} readStream
  27. * @return {Promise<Buffer>}
  28. */
  29. async function gunzipStreamToBuffer(readStream) {
  30. const gunzip = zlib.createGunzip()
  31. const bufferStream = new WritableBuffer()
  32. await pipeline(readStream, gunzip, bufferStream)
  33. return bufferStream.contents()
  34. }
  35. exports.gunzipStreamToBuffer = gunzipStreamToBuffer