1
0

add-stream.ts 989 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import * as Stream from 'stream';
  2. import { PassThrough, Writable } from 'stream';
  3. class Appendee extends PassThrough {
  4. constructor(private factory: any, private opts: any) {
  5. super(opts);
  6. }
  7. _flush(end: any) {
  8. const stream = this.factory();
  9. stream.pipe(new Appender(this, this.opts))
  10. .on('finish', end);
  11. stream.resume();
  12. }
  13. }
  14. class Appender extends Writable {
  15. constructor(private target: any, opts: any) {
  16. super(opts);
  17. }
  18. _write(chunk: any, enc: any, cb: any) {
  19. this.target.push(chunk);
  20. cb();
  21. }
  22. }
  23. /**
  24. * Append the contents of one stream onto another.
  25. * Based on https://github.com/wilsonjackson/add-stream
  26. */
  27. export function addStream(stream: any, opts?: any) {
  28. opts = opts || {};
  29. let factory;
  30. if (typeof stream === 'function') {
  31. factory = stream;
  32. } else {
  33. stream.pause();
  34. factory = () => stream;
  35. }
  36. return new Appendee(factory, opts);
  37. }