stuttered-pipe.js 1.56 KB
Newer Older
bovornsiriampairat committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
const events = require('events');

// =============================================================================
// StutteredPipe - Used to slow down streaming so GC can get a look in
class StutteredPipe extends events.EventEmitter {
  constructor(readable, writable, options) {
    super();

    options = options || {};

    this.readable = readable;
    this.writable = writable;
    this.bufSize = options.bufSize || 16384;
    this.autoPause = options.autoPause || false;

    this.paused = false;
    this.eod = false;
    this.scheduled = null;

    readable.on('end', () => {
      this.eod = true;
      writable.end();
    });

    // need to have some way to communicate speed of stream
    // back from the consumer
    readable.on('readable', () => {
      if (!this.paused) {
        this.resume();
      }
    });
    this._schedule();
  }

  pause() {
    this.paused = true;
  }

  resume() {
    if (!this.eod) {
      if (this.scheduled !== null) {
        clearImmediate(this.scheduled);
      }
      this._schedule();
    }
  }

  _schedule() {
    this.scheduled = setImmediate(() => {
      this.scheduled = null;
      if (!this.eod && !this.paused) {
        const data = this.readable.read(this.bufSize);
        if (data && data.length) {
          this.writable.write(data);

          if (!this.paused && !this.autoPause) {
            this._schedule();
          }
        } else if (!this.paused) {
          this._schedule();
        }
      }
    });
  }
}

module.exports = StutteredPipe;