through2.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const { Transform } = require('readable-stream')
  2. function inherits (fn, sup) {
  3. fn.super_ = sup
  4. fn.prototype = Object.create(sup.prototype, {
  5. constructor: { value: fn, enumerable: false, writable: true, configurable: true }
  6. })
  7. }
  8. // create a new export function, used by both the main export and
  9. // the .ctor export, contains common logic for dealing with arguments
  10. function through2 (construct) {
  11. return (options, transform, flush) => {
  12. if (typeof options === 'function') {
  13. flush = transform
  14. transform = options
  15. options = {}
  16. }
  17. if (typeof transform !== 'function') {
  18. // noop
  19. transform = (chunk, enc, cb) => cb(null, chunk)
  20. }
  21. if (typeof flush !== 'function') {
  22. flush = null
  23. }
  24. return construct(options, transform, flush)
  25. }
  26. }
  27. // main export, just make me a transform stream!
  28. const make = through2((options, transform, flush) => {
  29. const t2 = new Transform(options)
  30. t2._transform = transform
  31. if (flush) {
  32. t2._flush = flush
  33. }
  34. return t2
  35. })
  36. // make me a reusable prototype that I can `new`, or implicitly `new`
  37. // with a constructor call
  38. const ctor = through2((options, transform, flush) => {
  39. function Through2 (override) {
  40. if (!(this instanceof Through2)) {
  41. return new Through2(override)
  42. }
  43. this.options = Object.assign({}, options, override)
  44. Transform.call(this, this.options)
  45. this._transform = transform
  46. if (flush) {
  47. this._flush = flush
  48. }
  49. }
  50. inherits(Through2, Transform)
  51. return Through2
  52. })
  53. const obj = through2(function (options, transform, flush) {
  54. const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
  55. t2._transform = transform
  56. if (flush) {
  57. t2._flush = flush
  58. }
  59. return t2
  60. })
  61. module.exports = make
  62. module.exports.ctor = ctor
  63. module.exports.obj = obj