through.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const isFn = require('./isFn');
  2. const extend = require('./extend');
  3. const inherits = require('./inherits');
  4. const Transform = require('stream').Transform;
  5. exports = through(function(opts, transform, flush) {
  6. const t = new Transform(opts);
  7. t._transform = transform;
  8. if (flush) t._flush = flush;
  9. return t;
  10. });
  11. exports.obj = through(function(opts, transform, flush) {
  12. const t = new Transform(
  13. extend(
  14. {
  15. objectMode: true,
  16. highWaterMark: 16
  17. },
  18. opts
  19. )
  20. );
  21. t._transform = transform;
  22. if (flush) t._flush = flush;
  23. return t;
  24. });
  25. exports.ctor = through(function(opts, transform, flush) {
  26. function Through(override) {
  27. if (!(this instanceof Through)) return new Through(override);
  28. Transform.call(this, extend(opts, override));
  29. }
  30. inherits(Through, Transform);
  31. const proto = Through.prototype;
  32. proto._transform = transform;
  33. if (flush) proto._flush = flush;
  34. return Through;
  35. });
  36. function through(streamFactory) {
  37. return function(opts, transform, flush) {
  38. if (isFn(opts)) {
  39. flush = transform;
  40. transform = opts;
  41. opts = {};
  42. }
  43. if (!isFn(transform)) transform = defTransform;
  44. if (!isFn(flush)) flush = null;
  45. return streamFactory(opts, transform, flush);
  46. };
  47. }
  48. function defTransform(chunk, enc, cb) {
  49. cb(null, chunk);
  50. }
  51. module.exports = exports;