through2.js 2.1 KB

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