選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

through2.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. })