| 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 |
|
|---|
| 8 | const getOptions = options => ({level: 9, ...options});
|
|---|
| 9 | const gzip = promisify(zlib.gzip);
|
|---|
| 10 |
|
|---|
| 11 | module.exports = async (input, options) => {
|
|---|
| 12 | if (!input) {
|
|---|
| 13 | return 0;
|
|---|
| 14 | }
|
|---|
| 15 |
|
|---|
| 16 | const data = await gzip(input, getOptions(options));
|
|---|
| 17 | return data.length;
|
|---|
| 18 | };
|
|---|
| 19 |
|
|---|
| 20 | module.exports.sync = (input, options) => zlib.gzipSync(input, getOptions(options)).length;
|
|---|
| 21 |
|
|---|
| 22 | module.exports.stream = options => {
|
|---|
| 23 | const input = new stream.PassThrough();
|
|---|
| 24 | const output = new stream.PassThrough();
|
|---|
| 25 | const wrapper = duplexer(input, output);
|
|---|
| 26 |
|
|---|
| 27 | let gzipSize = 0;
|
|---|
| 28 | const gzip = zlib.createGzip(getOptions(options))
|
|---|
| 29 | .on('data', buf => {
|
|---|
| 30 | gzipSize += buf.length;
|
|---|
| 31 | })
|
|---|
| 32 | .on('error', () => {
|
|---|
| 33 | wrapper.gzipSize = 0;
|
|---|
| 34 | })
|
|---|
| 35 | .on('end', () => {
|
|---|
| 36 | wrapper.gzipSize = gzipSize;
|
|---|
| 37 | wrapper.emit('gzip-size', gzipSize);
|
|---|
| 38 | output.end();
|
|---|
| 39 | });
|
|---|
| 40 |
|
|---|
| 41 | input.pipe(gzip);
|
|---|
| 42 | input.pipe(output, {end: false});
|
|---|
| 43 |
|
|---|
| 44 | return wrapper;
|
|---|
| 45 | };
|
|---|
| 46 |
|
|---|
| 47 | module.exports.file = (path, options) => {
|
|---|
| 48 | return new Promise((resolve, reject) => {
|
|---|
| 49 | const stream = fs.createReadStream(path);
|
|---|
| 50 | stream.on('error', reject);
|
|---|
| 51 |
|
|---|
| 52 | const gzipStream = stream.pipe(module.exports.stream(options));
|
|---|
| 53 | gzipStream.on('error', reject);
|
|---|
| 54 | gzipStream.on('gzip-size', resolve);
|
|---|
| 55 | });
|
|---|
| 56 | };
|
|---|
| 57 |
|
|---|
| 58 | module.exports.fileSync = (path, options) => module.exports.sync(fs.readFileSync(path), options);
|
|---|