Convert Figma logo to code with AI

gildas-lormeau logozip.js

JavaScript library to zip and unzip files supporting multi-core compression, compression streams, zip64, split files and encryption.

3,387
510
3,387
1

Top Related Projects

11,394

A Minimalistic Wrapper for IndexedDB

An HTML5 saveAs() FileSaver implementation

StreamSaver writes stream to the filesystem directly asynchronous

9,737

Create, read and edit .zip files with Javascript

5,494

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

Quick Overview

zip.js is a JavaScript library that provides a comprehensive solution for creating, reading, and modifying ZIP archives directly in web browsers. It supports various compression methods and offers both synchronous and asynchronous APIs, making it versatile for different use cases in web applications.

Pros

  • Pure JavaScript implementation, requiring no external dependencies
  • Supports both client-side and server-side (Node.js) environments
  • Offers streaming capabilities for efficient handling of large files
  • Provides both synchronous and asynchronous APIs for flexibility

Cons

  • May have performance limitations with very large archives compared to native implementations
  • Documentation could be more comprehensive for advanced use cases
  • Limited support for some less common ZIP format features
  • Requires polyfills for older browsers to support some features

Code Examples

  1. Creating a ZIP file:
import * as zip from "@zip.js/zip.js";

const zipWriter = new zip.ZipWriter(new zip.BlobWriter("application/zip"));
await zipWriter.add("hello.txt", new zip.TextReader("Hello World!"));
const blob = await zipWriter.close();
  1. Reading a ZIP file:
import * as zip from "@zip.js/zip.js";

const zipReader = new zip.ZipReader(new zip.BlobReader(blob));
const entries = await zipReader.getEntries();
const fileText = await entries[0].getData(new zip.TextWriter());
console.log(fileText);
await zipReader.close();
  1. Streaming a large file:
import * as zip from "@zip.js/zip.js";

const zipReader = new zip.ZipReader(new zip.HttpReader("large-archive.zip"));
const entries = await zipReader.getEntries();
const writer = new zip.BlobWriter();
await entries[0].getData(writer, {
  onprogress: (index, max) => {
    console.log(`Progress: ${index / max * 100}%`);
  }
});
const blob = await writer.getData();
await zipReader.close();

Getting Started

To use zip.js in your project, first install it via npm:

npm install @zip.js/zip.js

Then, import and use it in your JavaScript code:

import * as zip from "@zip.js/zip.js";

async function createZip() {
  const zipWriter = new zip.ZipWriter(new zip.BlobWriter("application/zip"));
  await zipWriter.add("file1.txt", new zip.TextReader("Content of file 1"));
  await zipWriter.add("file2.txt", new zip.TextReader("Content of file 2"));
  const blob = await zipWriter.close();
  // Use the blob as needed (e.g., download or further processing)
}

createZip();

This example demonstrates creating a simple ZIP file with two text files. Adjust the code as needed for your specific use case.

Competitor Comparisons

11,394

A Minimalistic Wrapper for IndexedDB

Pros of Dexie.js

  • Provides a more high-level, user-friendly API for IndexedDB operations
  • Supports complex querying and indexing capabilities
  • Offers robust transaction handling and promise-based operations

Cons of Dexie.js

  • Larger library size compared to zip.js
  • Focused solely on IndexedDB, while zip.js handles ZIP file operations
  • May have a steeper learning curve for developers new to IndexedDB concepts

Code Comparison

Dexie.js example:

const db = new Dexie('MyDatabase');
db.version(1).stores({
  friends: '++id, name, age'
});
await db.friends.add({name: 'John', age: 30});

zip.js example:

const zipWriter = new zip.ZipWriter(new zip.BlobWriter("application/zip"));
await zipWriter.add("hello.txt", new zip.TextReader("Hello World!"));
const blob = await zipWriter.close();

While both libraries serve different purposes, Dexie.js excels in database operations and querying, whereas zip.js specializes in ZIP file manipulation. Dexie.js offers a more abstracted API for IndexedDB, making it easier to work with complex data structures and relationships. On the other hand, zip.js provides a straightforward way to create and manipulate ZIP files in JavaScript. The choice between the two depends on the specific requirements of your project.

An HTML5 saveAs() FileSaver implementation

Pros of FileSaver.js

  • Lightweight and focused solely on saving files in the browser
  • Simple API with broad browser support
  • Actively maintained with regular updates

Cons of FileSaver.js

  • Limited functionality compared to zip.js (no compression or archive handling)
  • Requires additional libraries for more complex file operations

Code Comparison

FileSaver.js:

import { saveAs } from 'file-saver';

const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

zip.js:

import * as zip from "@zip.js/zip.js";

const zipWriter = new zip.ZipWriter(new zip.BlobWriter("application/zip"));
await zipWriter.add("hello.txt", new zip.TextReader("Hello World!"));
const blob = await zipWriter.close();

Summary

FileSaver.js is a lightweight solution for saving files in the browser, while zip.js offers more comprehensive functionality for working with compressed archives. FileSaver.js is ideal for simple file saving tasks, whereas zip.js is better suited for projects requiring file compression and archive manipulation.

StreamSaver writes stream to the filesystem directly asynchronous

Pros of StreamSaver.js

  • Focuses specifically on saving large files or streams to disk efficiently
  • Utilizes the Streams API for better memory management and performance
  • Supports a wider range of browsers, including older versions

Cons of StreamSaver.js

  • Limited to file saving functionality, unlike zip.js which offers compression
  • Requires a service worker setup for full cross-browser compatibility
  • May have a steeper learning curve for developers unfamiliar with Streams API

Code Comparison

StreamSaver.js:

const fileStream = streamSaver.createWriteStream('filename.txt', {
  size: 22, // (optional) Will show progress
  writableStrategy: undefined, // (optional)
  readableStrategy: undefined  // (optional)
})

zip.js:

const zipWriter = new zip.ZipWriter(new zip.BlobWriter("application/zip"));
await zipWriter.add("filename.txt", new zip.TextReader("File content"));
const blob = await zipWriter.close();

StreamSaver.js is focused on efficient file saving using streams, while zip.js provides comprehensive ZIP file handling capabilities. StreamSaver.js offers better performance for large file downloads, but zip.js excels in compression and decompression tasks. The choice between them depends on specific project requirements, such as file size, compression needs, and browser compatibility.

9,737

Create, read and edit .zip files with Javascript

Pros of JSZip

  • More comprehensive API with support for various compression methods
  • Better browser compatibility, including older versions
  • Larger community and more frequent updates

Cons of JSZip

  • Larger file size, which may impact load times
  • Slightly more complex setup for basic operations
  • Higher memory usage for large files

Code Comparison

JSZip

var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.generateAsync({type:"blob"})
   .then(function(content) {
       saveAs(content, "example.zip");
   });

zip.js

zip.createWriter(new zip.BlobWriter("application/zip"), function(writer) {
    writer.add("Hello.txt", new zip.TextReader("Hello World\n"), function() {
        writer.close(function(blob) {
            saveAs(blob, "example.zip");
        });
    });
});

Both libraries offer similar functionality for creating and manipulating ZIP files in JavaScript. JSZip provides a more straightforward API with promise-based operations, while zip.js uses a callback-based approach. JSZip's syntax is generally more concise and easier to read, but zip.js may offer better performance for certain use cases, especially when dealing with large files or streaming operations.

5,494

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

Pros of pako

  • Smaller file size and faster performance for compression/decompression
  • Supports both browser and Node.js environments out of the box
  • Simpler API for basic compression and decompression tasks

Cons of pako

  • Limited to working with raw deflate/inflate algorithms
  • Lacks support for ZIP file format and associated features
  • No built-in support for handling large files or streaming

Code Comparison

pako:

var pako = require('pako');
var input = new Uint8Array([1,2,3,4,5]);
var compressed = pako.deflate(input);
var decompressed = pako.inflate(compressed);

zip.js:

zip.createWriter(new zip.BlobWriter("application/zip"), function(writer) {
  writer.add("hello.txt", new zip.TextReader("Hello World!"), function() {
    writer.close(function(blob) {
      // blob contains the zip file as a Blob object
    });
  });
});

The code examples highlight the simplicity of pako for basic compression tasks, while zip.js offers more comprehensive ZIP file handling capabilities.

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

Introduction

zip.js is a JavaScript open-source library (BSD-3-Clause license) for compressing and decompressing zip files. It has been designed to handle large amounts of data. It supports notably multi-core compression, native compression with compression streams, archives larger than 4GB with Zip64, split zip files and data encryption.

Demo

See https://gildas-lormeau.github.io/zip-manager

Documentation

See here for more info: https://gildas-lormeau.github.io/zip.js/

Examples

Hello world

import {
  BlobReader,
  BlobWriter,
  TextReader,
  TextWriter,
  ZipReader,
  ZipWriter,
} from "https://deno.land/x/zipjs/index.js";

// ----
// Write the zip file
// ----

// Creates a BlobWriter object where the zip content will be written.
const zipFileWriter = new BlobWriter();
// Creates a TextReader object storing the text of the entry to add in the zip
// (i.e. "Hello world!").
const helloWorldReader = new TextReader("Hello world!");

// Creates a ZipWriter object writing data via `zipFileWriter`, adds the entry
// "hello.txt" containing the text "Hello world!" via `helloWorldReader`, and
// closes the writer.
const zipWriter = new ZipWriter(zipFileWriter);
await zipWriter.add("hello.txt", helloWorldReader);
await zipWriter.close();

// Retrieves the Blob object containing the zip content into `zipFileBlob`. It
// is also returned by zipWriter.close() for more convenience.
const zipFileBlob = await zipFileWriter.getData();

// ----
// Read the zip file
// ----

// Creates a BlobReader object used to read `zipFileBlob`.
const zipFileReader = new BlobReader(zipFileBlob);
// Creates a TextWriter object where the content of the first entry in the zip
// will be written.
const helloWorldWriter = new TextWriter();

// Creates a ZipReader object reading the zip content via `zipFileReader`,
// retrieves metadata (name, dates, etc.) of the first entry, retrieves its
// content via `helloWorldWriter`, and closes the reader.
const zipReader = new ZipReader(zipFileReader);
const firstEntry = (await zipReader.getEntries()).shift();
const helloWorldText = await firstEntry.getData(helloWorldWriter);
await zipReader.close();

// Displays "Hello world!".
console.log(helloWorldText);

Run the code on JSFiddle: https://jsfiddle.net/dns7pkxt/

Hello world with Streams

import {
  BlobReader,
  ZipReader,
  ZipWriter,
} from "https://deno.land/x/zipjs/index.js";

// ----
// Write the zip file
// ----

// Creates a TransformStream object, the zip content will be written in the
// `writable` property.
const zipFileStream = new TransformStream();
// Creates a Promise object resolved to the zip content returned as a Blob
// object retrieved from `zipFileStream.readable`.
const zipFileBlobPromise = new Response(zipFileStream.readable).blob();
// Creates a ReadableStream object storing the text of the entry to add in the
// zip (i.e. "Hello world!").
const helloWorldReadable = new Blob(["Hello world!"]).stream();

// Creates a ZipWriter object writing data into `zipFileStream.writable`, adds
// the entry "hello.txt" containing the text "Hello world!" retrieved from
// `helloWorldReadable`, and closes the writer.
const zipWriter = new ZipWriter(zipFileStream.writable);
await zipWriter.add("hello.txt", helloWorldReadable);
await zipWriter.close();

// Retrieves the Blob object containing the zip content into `zipFileBlob`.
const zipFileBlob = await zipFileBlobPromise;

// ----
// Read the zip file
// ----

// Creates a BlobReader object used to read `zipFileBlob`.
const zipFileReader = new BlobReader(zipFileBlob);
// Creates a TransformStream object, the content of the first entry in the zip
// will be written in the `writable` property.
const helloWorldStream = new TransformStream();
// Creates a Promise object resolved to the content of the first entry returned
// as text from `helloWorldStream.readable`.
const helloWorldTextPromise = new Response(helloWorldStream.readable).text();

// Creates a ZipReader object reading the zip content via `zipFileReader`,
// retrieves metadata (name, dates, etc.) of the first entry, retrieves its
// content into `helloWorldStream.writable`, and closes the reader.
const zipReader = new ZipReader(zipFileReader);
const firstEntry = (await zipReader.getEntries()).shift();
await firstEntry.getData(helloWorldStream.writable);
await zipReader.close();

// Displays "Hello world!".
const helloWorldText = await helloWorldTextPromise;
console.log(helloWorldText);

Run the code on JSFiddle: https://jsfiddle.net/exnyq1ft/

Adding concurrently multiple entries in a zip file

import {
  BlobWriter,
  HttpReader,
  TextReader,
  ZipWriter,
} from "https://unpkg.com/@zip.js/zip.js/index.js";

const README_URL = "https://unpkg.com/@zip.js/zip.js/README.md";
getZipFileBlob()
  .then(downloadFile);

async function getZipFileBlob() {
  const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
  await Promise.all([
    zipWriter.add("hello.txt", new TextReader("Hello world!")),
    zipWriter.add("README.md", new HttpReader(README_URL)),
  ]);
  return zipWriter.close();
}

function downloadFile(blob) {
  document.body.appendChild(Object.assign(document.createElement("a"), {
    download: "hello.zip",
    href: URL.createObjectURL(blob),
    textContent: "Download zip file",
  }));
}

Run the code on Plunker: https://plnkr.co/edit/4sVljNIpqSUE9HCA?preview

Tests

See https://github.com/gildas-lormeau/zip.js/tree/master/tests/all

NPM DownloadsLast 30 Days