file_stream.js 1.18 KB
Newer Older
Li Mingzhe's avatar
Li Mingzhe 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
'use strict';

const tar = require('../tar');
const gzip = require('../gzip');
const utils = require('../utils');
const stream = require('stream');
const pump = require('pump');
const ready = require('get-ready');

class TgzFileStream extends stream.Transform {
  constructor(opts) {
    opts = opts || {};
    super(opts);

    const sourceType = this._sourceType = utils.sourceType(opts.source);

    const tarStream = this._tarStream = new tar.FileStream(opts);
    opts = utils.clone(opts);
    delete opts.source;
    const gzipStream = new gzip.FileStream(opts);

    gzipStream.on('data', chunk => {
      this.push(chunk);
    });
    gzipStream.on('end', () => this.ready(true));

    pump(tarStream, gzipStream, err => {
      err && this.emit('error', err);
    });

    if (sourceType !== 'stream' && sourceType !== undefined) {
      this.end();
    }
  }

  _transform(chunk, encoding, callback) {
    this._tarStream.write(chunk, encoding, callback);
  }

  _flush(callback) {
    if (this._sourceType === 'stream' || this._sourceType === undefined) {
      this._tarStream.end();
    }
    this.ready(callback);
  }
}

ready.mixin(TgzFileStream.prototype);
module.exports = TgzFileStream;