index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const fs = require('fs');
  3. const stream = require('stream');
  4. const zlib = require('zlib');
  5. const {promisify} = require('util');
  6. const duplexer = require('duplexer');
  7. const getOptions = options => ({level: 9, ...options});
  8. const gzip = promisify(zlib.gzip);
  9. module.exports = async (input, options) => {
  10. if (!input) {
  11. return 0;
  12. }
  13. const data = await gzip(input, getOptions(options));
  14. return data.length;
  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. };
  47. module.exports.fileSync = (path, options) => module.exports.sync(fs.readFileSync(path), options);