index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var PassThrough = require('stream').PassThrough;
  3. var Writable = require('stream').Writable;
  4. var util = require('util');
  5. util.inherits(Appendee, PassThrough);
  6. util.inherits(Appender, Writable);
  7. function Appendee(factory, opts) {
  8. PassThrough.call(this, opts);
  9. this.factory = factory;
  10. this.opts = opts;
  11. }
  12. //noinspection JSUnusedGlobalSymbols
  13. Appendee.prototype._flush = function (end) {
  14. var stream = this.factory();
  15. stream.pipe(new Appender(this, this.opts))
  16. .on('finish', end);
  17. stream.resume();
  18. };
  19. function Appender(target, opts) {
  20. Writable.call(this, opts);
  21. this.target = target;
  22. }
  23. //noinspection JSUnusedGlobalSymbols
  24. Appender.prototype._write = function (chunk, enc, cb) {
  25. this.target.push(chunk);
  26. cb();
  27. };
  28. function addStream(stream, opts) {
  29. opts = opts || {};
  30. var factory;
  31. if (typeof stream === 'function') {
  32. factory = stream;
  33. }
  34. else {
  35. stream.pause();
  36. factory = function () {
  37. return stream;
  38. };
  39. }
  40. return new Appendee(factory, opts);
  41. }
  42. addStream.obj = function (stream, opts) {
  43. opts = opts || {};
  44. opts.objectMode = true;
  45. return addStream(stream, opts);
  46. };
  47. module.exports = addStream;