index.js 1.4 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. return pify(zlib.gzip)(input, getOptions(options)).then(data => data.length).catch(_ => 0);
  13. };
  14. module.exports.sync = (input, options) => zlib.gzipSync(input, getOptions(options)).length;
  15. module.exports.stream = options => {
  16. const input = new stream.PassThrough();
  17. const output = new stream.PassThrough();
  18. const wrapper = duplexer(input, output);
  19. let gzipSize = 0;
  20. const gzip = zlib.createGzip(getOptions(options))
  21. .on('data', buf => {
  22. gzipSize += buf.length;
  23. })
  24. .on('error', () => {
  25. wrapper.gzipSize = 0;
  26. })
  27. .on('end', () => {
  28. wrapper.gzipSize = gzipSize;
  29. wrapper.emit('gzip-size', gzipSize);
  30. output.end();
  31. });
  32. input.pipe(gzip);
  33. input.pipe(output, {end: false});
  34. return wrapper;
  35. };
  36. module.exports.file = (path, options) => {
  37. return new Promise((resolve, reject) => {
  38. const stream = fs.createReadStream(path);
  39. stream.on('error', reject);
  40. const gzipStream = stream.pipe(module.exports.stream(options));
  41. gzipStream.on('error', reject);
  42. gzipStream.on('gzip-size', resolve);
  43. });
  44. };
  45. module.exports.fileSync = (path, options) => module.exports.sync(fs.readFileSync(path), options);