Convert Figma logo to code with AI

imaya logozlib.js

compact zlib, deflate, inflate, zip library in JavaScript

1,122
351
1,122
38

Top Related Projects

5,575

A massively spiffy yet delicately unobtrusive compression library.

5,494

high speed zlib port to javascript, works in browser & node.js

2,207

High performance (de)compression in an 8kB package

LZ-based compression algorithm for JavaScript

Quick Overview

zlib.js is a JavaScript implementation of the zlib compression library. It allows for compression and decompression of data directly in the browser or in Node.js environments, providing a pure JavaScript alternative to native zlib implementations.

Pros

  • Pure JavaScript implementation, enabling cross-platform compatibility
  • Supports both browser and Node.js environments
  • Offers various compression methods, including DEFLATE, INFLATE, and GZIP
  • Provides asynchronous processing options for improved performance

Cons

  • May have slower performance compared to native implementations
  • Limited maintenance and updates in recent years
  • Lacks some advanced features found in more recent compression libraries
  • Documentation could be more comprehensive

Code Examples

  1. Compressing a string:
const zlib = require('zlib.js');

const input = 'Hello, world!';
const compressed = zlib.deflate(input);
console.log(compressed);
  1. Decompressing data:
const zlib = require('zlib.js');

const compressed = /* compressed data */;
const decompressed = zlib.inflate(compressed);
console.log(decompressed.toString());
  1. Using GZIP compression:
const zlib = require('zlib.js');

const input = 'This is a longer string to compress';
const gzipped = zlib.gzip(input);
console.log(gzipped);

Getting Started

To use zlib.js in your project, follow these steps:

  1. Install the library using npm:

    npm install zlib.js
    
  2. Import the library in your JavaScript file:

    const zlib = require('zlib.js');
    
  3. Use the compression and decompression methods as needed:

    const compressed = zlib.deflate('Your data here');
    const decompressed = zlib.inflate(compressed);
    

Note: For browser usage, include the zlib.js file in your HTML and use the Zlib global object instead of requiring the module.

Competitor Comparisons

5,575

A massively spiffy yet delicately unobtrusive compression library.

Pros of zlib

  • Written in C, offering better performance for native applications
  • More comprehensive and feature-rich, supporting a wider range of compression algorithms
  • Widely used and battle-tested in many production environments

Cons of zlib

  • Requires compilation and is not directly usable in web browsers
  • Larger codebase and potentially more complex to integrate into projects
  • May have a steeper learning curve for developers unfamiliar with C

Code Comparison

zlib (C):

z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
deflateInit(&strm, level);

zlib.js (JavaScript):

var deflate = new Zlib.Deflate(data, {
  level: level,
  gzip: true
});
var compressed = deflate.compress();

Additional Notes

zlib.js is specifically designed for use in web browsers and Node.js environments, providing a pure JavaScript implementation of zlib compression algorithms. This makes it easier to integrate into web-based projects but may sacrifice some performance compared to the native C implementation of zlib.

zlib, on the other hand, is the original and widely-used compression library that serves as the foundation for many compression tools and libraries across various platforms. It offers more fine-grained control and potentially better performance for native applications.

5,494

high speed zlib port to javascript, works in browser & node.js

Pros of pako

  • More actively maintained with recent updates
  • Better performance, especially for larger files
  • Supports both Node.js and browser environments

Cons of pako

  • Slightly larger file size
  • Less comprehensive documentation

Code Comparison

zlib.js:

var compressed = zlib.deflate(input);
var decompressed = zlib.inflate(compressed);

pako:

var compressed = pako.deflate(input);
var decompressed = pako.inflate(compressed);

Both libraries offer similar APIs for basic compression and decompression operations. However, pako provides additional methods and options for more advanced use cases.

Performance

pako generally outperforms zlib.js, especially when dealing with larger files. This makes it a better choice for applications that require high-speed compression and decompression.

Compatibility

While zlib.js is primarily designed for browser use, pako supports both browser and Node.js environments, making it more versatile for different types of projects.

Community and Support

pako has a larger user base and more active development, which translates to better long-term support and more frequent updates. zlib.js, on the other hand, has not seen significant updates in recent years.

File Size

zlib.js has a slightly smaller file size, which may be beneficial for projects where every kilobyte counts. However, the difference is minimal and unlikely to impact most applications significantly.

2,207

High performance (de)compression in an 8kB package

Pros of fflate

  • Significantly faster compression and decompression speeds
  • Smaller bundle size, making it more suitable for browser-based applications
  • Supports more compression formats, including Gzip and Zlib

Cons of fflate

  • Less mature project with potentially fewer real-world use cases
  • May have less comprehensive documentation compared to zlib.js

Code Comparison

fflate:

import { gzip, ungzip } from 'fflate';

const compressed = gzip(new TextEncoder().encode('Hello, World!'));
const decompressed = ungzip(compressed);
console.log(new TextDecoder().decode(decompressed));

zlib.js:

const compressed = zlib.deflate(unescape(encodeURIComponent('Hello, World!')));
const decompressed = zlib.inflate(compressed);
console.log(decodeURIComponent(escape(decompressed)));

Summary

fflate offers improved performance and a smaller footprint compared to zlib.js, making it an attractive option for modern web applications. However, zlib.js has been around longer and may have more extensive documentation. The code comparison shows that fflate uses more modern APIs, while zlib.js relies on older encoding methods. Developers should consider their specific needs and target environments when choosing between these libraries.

LZ-based compression algorithm for JavaScript

Pros of lz-string

  • Smaller library size, making it more lightweight for web applications
  • Faster compression and decompression speeds for small to medium-sized data
  • Simpler API, easier to use for basic compression tasks

Cons of lz-string

  • Less compression efficiency for larger data sets compared to zlib.js
  • Limited compression algorithm options (LZ-based only)
  • Less widespread adoption and community support

Code Comparison

lz-string:

var compressed = LZString.compress("Hello, World!");
var decompressed = LZString.decompress(compressed);

zlib.js:

var compressed = zlib.deflate("Hello, World!");
var decompressed = zlib.inflate(compressed);

Summary

lz-string is a lightweight and fast compression library, ideal for small to medium-sized data in web applications. It offers a simpler API and faster processing times for smaller data sets. However, it may not be as efficient for larger data and has fewer compression options compared to zlib.js.

zlib.js, on the other hand, provides better compression ratios for larger data sets and offers more advanced compression algorithms. It has wider adoption and community support but comes with a larger library size and slightly more complex API.

Choose lz-string for quick, simple compression tasks in web applications, and zlib.js for more robust compression needs or when dealing with larger data sets.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

zlib.js

Greenkeeper badge

Build Status

English version

zlib.js は ZLIB(RFC1950), DEFLATE(RFC1951), GZIP(RFC1952), PKZIP の JavaScript 実装です。

使い方

zlib.js は必要な機能ごとに分割されています。 bin ディレクトリから必要なものを利用してください。

  • zlib_and_gzip.min.js: ZLIB + GZIP
    • (Raw)
      • rawdeflate.js: Raw Deflate
      • raw.js: Raw Inflate
    • zlib.min.js: ZLIB Inflate + Deflate
      • inflate.min.js: ZLIB Inflate
      • deflate.min.js: ZLIB Deflate
      • inflate_stream.min.js: ZLIB Inflate (stream mode)
    • (GZIP)
      • gzip.min.js: GZIP
      • gunzip.min.js: GUNZIP
    • (PKZIP)
      • zip.min.js ZIP
      • unzip.min.js UNZIP
  • node-zlib.js: (ZLIB + GZIP for node.js)

圧縮 (Compress)

Raw Deflate

// plain = Array.<number> or Uint8Array
var deflate = new Zlib.RawDeflate(plain);
var compressed = deflate.compress();

Raw Deflate Option

ZLIB Option を参照してください。

ZLIB

// plain = Array.<number> or Uint8Array
var deflate = new Zlib.Deflate(plain);
var compressed = deflate.compress();
ZLIB Option

Zlib.Deflate の第二引数にオブジェクトを渡す事で圧縮オプションを指定する事が出来ます。

{
    compressionType: Zlib.Deflate.CompressionType, // 圧縮タイプ
    lazy: number // lazy matching の閾値
}

Zlib.Deflate.CompressionType は NONE(無圧縮), FIXED(固定ハフマン符号), DYNAMIC(動的ハフマン符号) から選択する事ができます。 default は DYNAMIC です。

lazy は Lazy Matching の閾値を指定します。 Lazy Matching とは、LZSS のマッチ長が閾値より低かった場合、次の Byte から LZSS の最長一致を試み、マッチ長の長い方を選択する手法です。

GZIP

GZIP の実装は現在不完全ですが、ただの圧縮コンテナとして使用する場合には特に問題はありません。 zlib.js を用いて作成された GZIP の OS は、自動的に UNKNOWN に設定されます。

// plain = Array.<number> or Uint8Array
var gzip = new Zlib.Gzip(plain);
var compressed = gzip.compress();
GZIP Option
{
    deflateOptions: Object, // deflate option (ZLIB Option 参照)
    flags: {
        fname: boolean, // ファイル名を使用するか
        comment: boolean, // コメントを使用するか
        fhcrc: boolean // FHCRC を使用するか
    },
    filename: string, // flags.fname が true のときに書き込むファイル名
    comment: string // flags.comment が true のときに書き込むコメント
}

PKZIP

PKZIP では複数のファイルを扱うため、他のものとは少し使い方が異なります。

var zip = new Zlib.Zip();
// plainData1
zip.addFile(plainData1, {
    filename: stringToByteArray('foo.txt')
});
zip.addFile(plainData2, {
    filename: stringToByteArray('bar.txt')
});
zip.addFile(plainData3, {
    filename: stringToByteArray('baz.txt')
});
var compressed = zip.compress();

function stringToByteArray(str) {
    var array = new (window.Uint8Array !== void 0 ? Uint8Array : Array)(str.length);
    var i;
    var il;

    for (i = 0, il = str.length; i < il; ++i) {
        array[i] = str.charCodeAt(i) & 0xff;
    }

    return array;
}
PKZIP Option

filename, comment, extraField は Typed Array が使用可能な場合は必ず Uint8Array を使用してください。

{
    filename: (Array.<number>|Uint8Array), // ファイル名
    comment: (Array.<number>|Uint8Array), // コメント
    extraField: (Array.<number>|Uint8Array), // その他の領域
    compress: boolean, // addFile メソッドを呼んだときに圧縮するか (通常は compress メソッドの呼び出し時に圧縮)
    compressionMethod: Zlib.Zip.CompressionMethod, // STORE or DEFLATE
    os: Zlib.Zip.OperatingSystem, // MSDOS or UNIX or MACINTOSH
    deflateOption: Object // see: ZLIB Option
}

伸張 (Decompress)

圧縮されたデータの伸張は、基本的に各コンストラクタに圧縮されたデータを渡し、 それの decompress メソッドを呼ぶ事で伸張処理を開始する事が出来ます。

Raw Deflate

// compressed = Array.<number> or Uint8Array
var inflate = new Zlib.RawInflate(compressed);
var plain = inflate.decompress();

Raw Deflate Option

ZLIB Option を参照してください。

ZLIB

// compressed = Array.<number> or Uint8Array
var inflate = new Zlib.Inflate(compressed);
var plain = inflate.decompress();
ZLIB Option

Zlib.Inflate の第二引数にオブジェクトを渡す事で伸張オプションを指定する事ができます。

{
    'index': number, // 入力バッファの開始位置
    'bufferSize': number, // 出力バッファの初期サイズ
    'bufferType': Zlib.Inflate.BufferType, // バッファの管理方法
    'resize': boolean, // 出力バッファのリサイズ
    'verify': boolean  // 伸張結果の検証を行うか
}

Zlib.Inflate.BufferType は ADAPTIVE(default) か BLOCK を選択する事ができます。

  • ADAPTIVE はバッファを伸張後のサイズを予測して一気に拡張しますが、データによっては余分にメモリを使用しすぎる事があります。
  • BLOCK では BufferSize ずつ拡張していきますが、動作はあまり速くありません。

resize オプションは Typed Array 利用可能時 decompress メソッドで返却する値の ArrayBuffer を Uint8Array の長さまで縮小させます。 default は false です。

verify オプションは Adler-32 Checksum の検証を行うかを指定します。 default は false です。

GZIP

// compressed = Array.<number> or Uint8Array
var gunzip = new Zlib.Gunzip(compressed);
var plain = gunzip.decompress();

Gunzip のオプションは現在ありません。

PKZIP

PKZIP の構築と同様に複数ファイルを扱うため、他のものとは少し使い方が異なります。

// compressed = Array.<number> or Uint8Array
var unzip = new Zlib.Unzip(compressed);
var filenames = unzip.getFilenames();
var plain = unzip.decompress(filenames[0]);

Unzip のオプションは現在ありません。

Node.js

Node.js で使用する場合はユニットテストを参照してください。 https://github.com/imaya/zlib.js/blob/master/test/node-test.js

Debug

zlib.js では JavaScript ファイルを minify された形で提供していますが、開発中やデバッグ時に minify する前の状態が知りたい事があります。 そういった時のために SourceMaps ファイルや Pretty Print されたファイルも提供しています。

Source Map

Source Map を使いたい場合はファイル名に dev のついたバージョンを使います。 例えば Source Map を有効にした Inflate を使いたい場合は以下になります。

- inflate.min.js // リリースバージョン
- inflate.dev.min.js // 開発バージョン(これを使う)

Pretty Print

SourceMaps とは異なりますが、minify の変数名の短縮のみ避けられれば良いという場合には、 Closure Compiler で読みやすくしたファイルを利用することも可能です。 zlib.pretty.js というファイル名で全ての実装がはいっていますので、minify されたものをこのファイルに置き換えるだけで使用できます。

How to build

ビルドは Grunt と Closure Compiler を使用して行います。

必要な環境

  • Grunt
  • Python

ビルド

Grunt を使ってビルドを行います。

$ grunt [target]

ビルドターゲット

targetファイル名含まれる実装
depsdeps.js依存関係の解決
deflatedeflate.min.jsZLIB Deflate
inflateinflate.min.jsZLIB Inflate
inflate_streaminlfate_stream.min.jsZLIB Inlate (stream)
zlibzlib.min.jsZLIB Deflate + Inflate
gzipgzip.min.jsGZIP Compression
gunzipgunzip.min.jsGZIP Decompression
zlib_and_gzipzlib_and_gzip.min.jsZLIB + GZIP
nodenode-zlib.jsZLIB + GZIP for node.js
zipzip.min.jsPKZIP Compression
unzipunzip.min.jsPKZIP Decompression
all*default target

テスト

ブラウザでは Karma, Node.js では mocha を使ってテストを行います。

$ npm test

ブラウザのみのテスト

$ npm run test-karma

Node.js のみのテスト

$ npm run test-mocha

Issue

現在プリセット辞書を用いた圧縮形式には対応していません。 プリセット辞書は通常の圧縮では利用されないため、影響は少ないと思います。

ライセンス

Copyright © 2012 imaya. Licensed under the MIT License.

NPM DownloadsLast 30 Days