through2.js 2.1 KB

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