index.js 951 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. var duplexer = require('duplexer');
  3. var stream = require('stream');
  4. var zlib = require('zlib');
  5. var opts = {level: 9};
  6. module.exports = function (str, cb) {
  7. if (!str) {
  8. cb(null, 0);
  9. return;
  10. }
  11. zlib.gzip(str, opts, function (err, data) {
  12. if (err) {
  13. cb(err, 0);
  14. return;
  15. }
  16. cb(err, data.length);
  17. });
  18. };
  19. module.exports.sync = function (str) {
  20. return zlib.gzipSync(str, opts).length;
  21. };
  22. module.exports.stream = function () {
  23. var input = new stream.PassThrough();
  24. var output = new stream.PassThrough();
  25. var wrapper = duplexer(input, output);
  26. var gzipSize = 0;
  27. var gzip = zlib.createGzip(opts)
  28. .on('data', function (buf) {
  29. gzipSize += buf.length;
  30. })
  31. .on('error', function () {
  32. wrapper.gzipSize = 0;
  33. })
  34. .on('end', function () {
  35. wrapper.gzipSize = gzipSize;
  36. wrapper.emit('gzip-size', gzipSize);
  37. output.end();
  38. });
  39. input.pipe(gzip);
  40. input.pipe(output, {end: false});
  41. return wrapper;
  42. };