streams.js 2.4 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 stringToStream = require('string-to-stream')
  10. function promiseWriteStreamFinish(writeStream) {
  11. return new BPromise(function (resolve, reject) {
  12. writeStream.on('finish', resolve)
  13. writeStream.on('error', reject)
  14. })
  15. }
  16. function promisePipe(readStream, writeStream) {
  17. readStream.pipe(writeStream)
  18. return promiseWriteStreamFinish(writeStream)
  19. }
  20. /**
  21. * Pipe a read stream to a write stream. The promise resolves when the write
  22. * stream finishes.
  23. *
  24. * @function
  25. * @param {stream.Readable} readStream
  26. * @param {stream.Writable} writeStream
  27. * @return {Promise}
  28. */
  29. exports.promisePipe = promisePipe
  30. function readStreamToBuffer(readStream) {
  31. return new BPromise(function (resolve, reject) {
  32. const buffers = []
  33. readStream.on('readable', function () {
  34. while (true) {
  35. const buffer = this.read()
  36. if (!buffer) {
  37. break
  38. }
  39. buffers.push(buffer)
  40. }
  41. })
  42. readStream.on('end', function () {
  43. resolve(Buffer.concat(buffers))
  44. })
  45. readStream.on('error', reject)
  46. })
  47. }
  48. /**
  49. * Create a promise for the result of reading a stream to a buffer.
  50. *
  51. * @function
  52. * @param {stream.Readable} readStream
  53. * @return {Promise.<Buffer>}
  54. */
  55. exports.readStreamToBuffer = readStreamToBuffer
  56. function gunzipStreamToBuffer(readStream) {
  57. const gunzip = zlib.createGunzip()
  58. const gunzipStream = readStream.pipe(gunzip)
  59. return new BPromise(function (resolve, reject) {
  60. const buffers = []
  61. gunzipStream.on('data', function (buffer) {
  62. buffers.push(buffer)
  63. })
  64. gunzipStream.on('end', function () {
  65. resolve(Buffer.concat(buffers))
  66. })
  67. readStream.on('error', reject)
  68. gunzipStream.on('error', reject)
  69. })
  70. }
  71. /**
  72. * Create a promise for the result of un-gzipping a stream to a buffer.
  73. *
  74. * @function
  75. * @param {stream.Readable} readStream
  76. * @return {Promise.<Buffer>}
  77. */
  78. exports.gunzipStreamToBuffer = gunzipStreamToBuffer
  79. function gzipStringToStream(string) {
  80. const gzip = zlib.createGzip()
  81. return stringToStream(string).pipe(gzip)
  82. }
  83. /**
  84. * Create a write stream that gzips the given string.
  85. *
  86. * @function
  87. * @param {string} string
  88. * @return {stream.Writable}
  89. */
  90. exports.gzipStringToStream = gzipStringToStream