index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. const fs = require('fs');
  3. const stream = require('stream');
  4. const zlib = require('zlib');
  5. const duplexer = require('duplexer');
  6. const pify = require('pify');
  7. const getOptions = options => Object.assign({level: 9}, options);
  8. module.exports = (input, options) => {
  9. if (!input) {
  10. return Promise.resolve(0);
  11. }
  12. // TODO: Remove below comment when new XO release is out
  13. // eslint-disable-next-line no-unused-vars, unicorn/catch-error-name
  14. return pify(zlib.gzip)(input, getOptions(options)).then(data => data.length).catch(_ => 0);
  15. };
  16. module.exports.sync = (input, options) => zlib.gzipSync(input, getOptions(options)).length;
  17. module.exports.stream = options => {
  18. const input = new stream.PassThrough();
  19. const output = new stream.PassThrough();
  20. const wrapper = duplexer(input, output);
  21. let gzipSize = 0;
  22. const gzip = zlib.createGzip(getOptions(options))
  23. .on('data', buf => {
  24. gzipSize += buf.length;
  25. })
  26. .on('error', () => {
  27. wrapper.gzipSize = 0;
  28. })
  29. .on('end', () => {
  30. wrapper.gzipSize = gzipSize;
  31. wrapper.emit('gzip-size', gzipSize);
  32. output.end();
  33. });
  34. input.pipe(gzip);
  35. input.pipe(output, {end: false});
  36. return wrapper;
  37. };
  38. module.exports.file = (path, options) => {
  39. return new Promise((resolve, reject) => {
  40. const stream = fs.createReadStream(path);
  41. stream.on('error', reject);
  42. const gzipStream = stream.pipe(module.exports.stream(options));
  43. gzipStream.on('error', reject);
  44. gzipStream.on('gzip-size', resolve);
  45. });
  46. };