File: index.js

package info (click to toggle)
node-gzip-size 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 160 kB
  • sloc: javascript: 381; makefile: 2
file content (58 lines) | stat: -rw-r--r-- 1,461 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict';
const fs = require('fs');
const stream = require('stream');
const zlib = require('zlib');
const {promisify} = require('util');
const duplexer = require('duplexer');

const getOptions = options => ({level: 9, ...options});
const gzip = promisify(zlib.gzip);

module.exports = async (input, options) => {
	if (!input) {
		return 0;
	}

	const data = await gzip(input, getOptions(options));
	return data.length;
};

module.exports.sync = (input, options) => zlib.gzipSync(input, getOptions(options)).length;

module.exports.stream = options => {
	const input = new stream.PassThrough();
	const output = new stream.PassThrough();
	const wrapper = duplexer(input, output);

	let gzipSize = 0;
	const gzip = zlib.createGzip(getOptions(options))
		.on('data', buf => {
			gzipSize += buf.length;
		})
		.on('error', () => {
			wrapper.gzipSize = 0;
		})
		.on('end', () => {
			wrapper.gzipSize = gzipSize;
			wrapper.emit('gzip-size', gzipSize);
			output.end();
		});

	input.pipe(gzip);
	input.pipe(output, {end: false});

	return wrapper;
};

module.exports.file = (path, options) => {
	return new Promise((resolve, reject) => {
		const stream = fs.createReadStream(path);
		stream.on('error', reject);

		const gzipStream = stream.pipe(module.exports.stream(options));
		gzipStream.on('error', reject);
		gzipStream.on('gzip-size', resolve);
	});
};

module.exports.fileSync = (path, options) => module.exports.sync(fs.readFileSync(path), options);