index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const Minipass = require('minipass')
  2. const _data = Symbol('_data')
  3. const _length = Symbol('_length')
  4. class Collect extends Minipass {
  5. constructor (options) {
  6. super(options)
  7. this[_data] = []
  8. this[_length] = 0
  9. }
  10. write (chunk, encoding, cb) {
  11. if (typeof encoding === 'function')
  12. cb = encoding, encoding = 'utf8'
  13. if (!encoding)
  14. encoding = 'utf8'
  15. const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
  16. this[_data].push(c)
  17. this[_length] += c.length
  18. if (cb)
  19. cb()
  20. return true
  21. }
  22. end (chunk, encoding, cb) {
  23. if (typeof chunk === 'function')
  24. cb = chunk, chunk = null
  25. if (typeof encoding === 'function')
  26. cb = encoding, encoding = 'utf8'
  27. if (chunk)
  28. this.write(chunk, encoding)
  29. const result = Buffer.concat(this[_data], this[_length])
  30. super.write(result)
  31. return super.end(cb)
  32. }
  33. }
  34. module.exports = Collect
  35. // it would be possible to DRY this a bit by doing something like
  36. // this.collector = new Collect() and listening on its data event,
  37. // but it's not much code, and we may as well save the extra obj
  38. class CollectPassThrough extends Minipass {
  39. constructor (options) {
  40. super(options)
  41. this[_data] = []
  42. this[_length] = 0
  43. }
  44. write (chunk, encoding, cb) {
  45. if (typeof encoding === 'function')
  46. cb = encoding, encoding = 'utf8'
  47. if (!encoding)
  48. encoding = 'utf8'
  49. const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
  50. this[_data].push(c)
  51. this[_length] += c.length
  52. return super.write(chunk, encoding, cb)
  53. }
  54. end (chunk, encoding, cb) {
  55. if (typeof chunk === 'function')
  56. cb = chunk, chunk = null
  57. if (typeof encoding === 'function')
  58. cb = encoding, encoding = 'utf8'
  59. if (chunk)
  60. this.write(chunk, encoding)
  61. const result = Buffer.concat(this[_data], this[_length])
  62. this.emit('collect', result)
  63. return super.end(cb)
  64. }
  65. }
  66. module.exports.PassThrough = CollectPassThrough