streams.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Promises are promises and streams are streams, and ne'er the twain shall
  3. * meet.
  4. * @module
  5. */
  6. 'use strict'
  7. const BPromise = require('bluebird')
  8. const zlib = require('zlib')
  9. const { WritableBuffer, ReadableString } = require('@overleaf/stream-utils')
  10. const { pipeline } = require('stream')
  11. function promisePipe(readStream, writeStream) {
  12. return new BPromise(function (resolve, reject) {
  13. pipeline(readStream, writeStream, function (err) {
  14. if (err) {
  15. reject(err)
  16. } else {
  17. resolve()
  18. }
  19. })
  20. })
  21. }
  22. /**
  23. * Pipe a read stream to a write stream. The promise resolves when the write
  24. * stream finishes.
  25. *
  26. * @function
  27. * @param {stream.Readable} readStream
  28. * @param {stream.Writable} writeStream
  29. * @return {Promise}
  30. */
  31. exports.promisePipe = promisePipe
  32. function readStreamToBuffer(readStream) {
  33. return new BPromise(function (resolve, reject) {
  34. const bufferStream = new WritableBuffer()
  35. pipeline(readStream, bufferStream, function (err) {
  36. if (err) {
  37. reject(err)
  38. } else {
  39. resolve(bufferStream.contents())
  40. }
  41. })
  42. })
  43. }
  44. /**
  45. * Create a promise for the result of reading a stream to a buffer.
  46. *
  47. * @function
  48. * @param {stream.Readable} readStream
  49. * @return {Promise.<Buffer>}
  50. */
  51. exports.readStreamToBuffer = readStreamToBuffer
  52. function gunzipStreamToBuffer(readStream) {
  53. const gunzip = zlib.createGunzip()
  54. const bufferStream = new WritableBuffer()
  55. return new BPromise(function (resolve, reject) {
  56. pipeline(readStream, gunzip, bufferStream, function (err) {
  57. if (err) {
  58. reject(err)
  59. } else {
  60. resolve(bufferStream.contents())
  61. }
  62. })
  63. })
  64. }
  65. /**
  66. * Create a promise for the result of un-gzipping a stream to a buffer.
  67. *
  68. * @function
  69. * @param {stream.Readable} readStream
  70. * @return {Promise.<Buffer>}
  71. */
  72. exports.gunzipStreamToBuffer = gunzipStreamToBuffer
  73. function gzipStringToStream(string) {
  74. const gzip = zlib.createGzip()
  75. return new ReadableString(string).pipe(gzip)
  76. }
  77. /**
  78. * Create a write stream that gzips the given string.
  79. *
  80. * @function
  81. * @param {string} string
  82. * @return {stream.Writable}
  83. */
  84. exports.gzipStringToStream = gzipStringToStream