dfrankland / wasm-zopfli

🗜 WebAssembly compiled Zopfli library
https://www.npmjs.com/package/wasm-zopfli
17 stars 0 forks source link

wasm-zopfli

WebAssembly compiled Zopfli library.

Installation

npm install -S wasm-zopfli

The awesome thing about wasm-zopfli is that it does not need to compile or download any prebuilt binaries!

Usage

Because WebAssembly is supported on both Node.js and several browsers, wasm-zopfli is super easy to use.

Node.js

An example of compressing something and saving it to a file via Node.js.

import { gzip } from 'wasm-zopfli';
import { writeFile } from 'fs';
import { promisify } from 'util';

const writeFileAsync = promisify(writeFile);

const content = Buffer.from('Hello, world!', 'utf8');

(async () => {
  try {
    const compressedContent = await gzip(content);
    await writeFileAsync('./hello_world.txt.gz', compressedContent);
  } catch (err) {
    console.error(err);
  }
})();

Browser

An example of compressing something and downloading it from the browser.

import { gzip } from 'wasm-zopfli';

const content = new TextEncoder('utf-8').encode('Hello, world!');

(async () => {
  try {
    const compressedContent = await gzip(content);

    const file = new File([compressedContent], 'hello_world.txt.gz', { type: 'application/gzip' });

    const link = document.createElement('a');
    link.setAttribute('href', URL.createObjectURL(file));
    link.setAttribute('download', file.name);
    link.click();
  } catch (err) {
    console.error(err);
  }
})();

Documentation

deflate(data)

Compress data using deflate. This is is referred to as "deflate raw" by Node.js' documentation.

gzip(data)

Compress data using gzip.

zlib(data)

Compress data using zlib. This is is referred to as "deflate" by Node.js' documentation.

zopfli(format, data)

The function that deflate, gzip, and zlib wrap. Pass any of the constants below and data to compress.

FORMAT_DEFLATE

Constant, reference, for compressing data with zopfli using deflate.

FORMAT_GZIP

Constant, reference, for compressing data with zopfli using gzip.

FORMAT_ZLIB

Constant, reference, for compressing data with zopfli using zlib.

Benchmark

Want to see how fast this is? Go to the benchmark directory to see results, instructions on running your own benchmark, and more.

Development

To build wasm-zopfli you will need to install Docker, and pull rustlang/rust:nightly. After that all that is needed is to do the following:

  1. Install all dependencies.
npm install
  1. Build the module.
npm run build
  1. Test the module.
npm test