aboutsummaryrefslogtreecommitdiff
path: root/node_modules/gulp-gzip/lib/compress.js
blob: db04c4c23c10b1845f0c0fd1cba9795055f25315 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var zlib     = require('zlib');
var Readable = require('stream').Readable;
var toArray  = require('stream-to-array');

function convertContentsToBuffer(contents, callback) {
  if (contents instanceof Buffer) {
    callback(null, contents);
  } else {
    toArray(contents, function (err, chunks) {
      if (err) {
        callback(err, null);
        return;
      }

      callback(null, Buffer.concat(chunks));
    });
  }
}

function convertContentsToStream(contents, callback) {
  if (contents instanceof Readable) {
    callback(null, contents);
  } else {
  var rs = new Readable({ objectMode: true });
    rs._read = function() {
      rs.push(contents);
      rs.push(null);
    };
    callback(null, rs);
  }
}

module.exports = function(originalContents, options, callback) {

  convertContentsToBuffer(originalContents, function(err, contentsAsBuffer) {
    if (err) {
      callback(err, null, false);
      return;
    }

    var originalContentLength = contentsAsBuffer.length;

    // Check if the threshold option is set
    // If true, check if the buffer length is greater than the threshold
    if (options.threshold && originalContentLength < options.threshold) {
      // File size is smaller than the threshold
      // Pass it along to the next plugin without compressing
        if (originalContents instanceof Buffer) {
          callback(null, contentsAsBuffer, false);
        } else {
          convertContentsToStream(contentsAsBuffer, function(err, contentsAsStream) {
            callback(null, contentsAsStream, false);
          });
        }
      return;
    }

    convertContentsToStream(contentsAsBuffer, function(err, contentsAsStream) {
      if (err) {
        callback(err, null, false);
        return;
      }

      // Compress the contents
      var gzipStream = zlib.createGzip(options.gzipOptions);
      contentsAsStream.pipe(gzipStream);

      convertContentsToBuffer(gzipStream, function(err, compressedContentsAsBuffer) {
        if (err) {
          callback(err, null, false);
          return;
        }

        if (options.skipGrowingFiles && compressedContentsAsBuffer.length >= originalContentLength) {
          callback(null, originalContents, false);
        } else {
          if (originalContents instanceof Buffer) {
            callback(null, compressedContentsAsBuffer, true);
          } else {
            convertContentsToStream(compressedContentsAsBuffer, function(err, compressedContentsStream) {
              callback(null, compressedContentsStream, true);
            });
          }
        }
      });
    });
  });
};