streams.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. /**
  12. * Pipe a read stream to a write stream. The promise resolves when the write
  13. * stream finishes.
  14. *
  15. * @function
  16. * @param {stream.Readable} readStream
  17. * @param {stream.Writable} writeStream
  18. * @return {Promise}
  19. */
  20. function promisePipe(readStream, writeStream) {
  21. return new BPromise(function (resolve, reject) {
  22. pipeline(readStream, writeStream, function (err) {
  23. if (err) {
  24. reject(err)
  25. } else {
  26. resolve()
  27. }
  28. })
  29. })
  30. }
  31. exports.promisePipe = promisePipe
  32. /**
  33. * Create a promise for the result of reading a stream to a buffer.
  34. *
  35. * @function
  36. * @param {stream.Readable} readStream
  37. * @return {Promise.<Buffer>}
  38. */
  39. function readStreamToBuffer(readStream) {
  40. return new BPromise(function (resolve, reject) {
  41. const bufferStream = new WritableBuffer()
  42. pipeline(readStream, bufferStream, function (err) {
  43. if (err) {
  44. reject(err)
  45. } else {
  46. resolve(bufferStream.contents())
  47. }
  48. })
  49. })
  50. }
  51. exports.readStreamToBuffer = readStreamToBuffer
  52. /**
  53. * Create a promise for the result of un-gzipping a stream to a buffer.
  54. *
  55. * @function
  56. * @param {stream.Readable} readStream
  57. * @return {Promise.<Buffer>}
  58. */
  59. function gunzipStreamToBuffer(readStream) {
  60. const gunzip = zlib.createGunzip()
  61. const bufferStream = new WritableBuffer()
  62. return new BPromise(function (resolve, reject) {
  63. pipeline(readStream, gunzip, bufferStream, function (err) {
  64. if (err) {
  65. reject(err)
  66. } else {
  67. resolve(bufferStream.contents())
  68. }
  69. })
  70. })
  71. }
  72. exports.gunzipStreamToBuffer = gunzipStreamToBuffer
  73. /**
  74. * Create a write stream that gzips the given string.
  75. *
  76. * @function
  77. * @param {string} string
  78. * @return {Promise.<stream.Readable>}
  79. */
  80. function gzipStringToStream(string) {
  81. return new BPromise(function (resolve, reject) {
  82. zlib.gzip(Buffer.from(string), function (error, result) {
  83. if (error) {
  84. reject(error)
  85. } else {
  86. resolve(new ReadableString(result))
  87. }
  88. })
  89. })
  90. }
  91. exports.gzipStringToStream = gzipStringToStream