CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jszip

Create, read and edit .zip files with JavaScript in both browser and Node.js environments

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

generation.mddocs/

ZIP Generation

Generate ZIP files in various output formats with compression options, progress tracking, and platform-specific optimizations. Supports asynchronous generation, streaming output, and customizable compression settings.

Capabilities

Asynchronous Generation

Generate complete ZIP files asynchronously in various output formats.

/**
 * Generate ZIP file asynchronously
 * @param options - Generation options including output type and compression
 * @param onUpdate - Optional progress callback function
 * @returns Promise resolving to the generated ZIP in the specified format
 */
generateAsync<T extends OutputType>(
  options?: JSZipGeneratorOptions<T>, 
  onUpdate?: OnUpdateCallback
): Promise<OutputByType[T]>;

Usage Examples:

import JSZip from "jszip";

const zip = new JSZip();
zip.file("hello.txt", "Hello World");
zip.file("data.json", JSON.stringify({foo: "bar"}));

// Generate as Blob (for browsers)
const blob = await zip.generateAsync({type: "blob"});

// Generate as ArrayBuffer
const arrayBuffer = await zip.generateAsync({type: "arraybuffer"});

// Generate as Base64 string
const base64 = await zip.generateAsync({type: "base64"});

// Generate as Node.js Buffer
const buffer = await zip.generateAsync({type: "nodebuffer"});

// Generate with compression options
const compressedBlob = await zip.generateAsync({
  type: "blob",
  compression: "DEFLATE",
  compressionOptions: { level: 9 }
});

// Generate with progress tracking
const zipWithProgress = await zip.generateAsync(
  { type: "blob" },
  (metadata) => {
    console.log(`Progress: ${metadata.percent}%`);
    console.log(`Current file: ${metadata.currentFile}`);
  }
);

Node.js Stream Generation

Generate ZIP files as Node.js ReadableStream for efficient handling of large archives.

/**
 * Generate ZIP as Node.js ReadableStream
 * @param options - Generation options (type is always 'nodebuffer')
 * @param onUpdate - Optional progress callback function
 * @returns Node.js ReadableStream containing the ZIP data
 */
generateNodeStream(
  options?: JSZipGeneratorOptions<'nodebuffer'>, 
  onUpdate?: OnUpdateCallback
): NodeJS.ReadableStream;

Usage Examples:

import JSZip from "jszip";
import fs from "fs";

const zip = new JSZip();
zip.file("large-file.txt", largeTextContent);

// Generate as stream and pipe to file
const stream = zip.generateNodeStream({
  compression: "DEFLATE",
  streamFiles: true
});

stream.pipe(fs.createWriteStream("output.zip"));

// Handle stream events
stream.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes`);
});

stream.on('end', () => {
  console.log('ZIP generation complete');
});

// Generate with progress tracking
const progressStream = zip.generateNodeStream(
  { compression: "DEFLATE" },
  (metadata) => {
    console.log(`Progress: ${metadata.percent}%`);
  }
);

Internal Stream Generation

Generate ZIP using the internal StreamHelper for advanced streaming scenarios.

/**
 * Generate ZIP using internal streaming implementation
 * @param options - Generation options
 * @returns JSZipStreamHelper for advanced stream handling
 */
generateInternalStream<T extends OutputType>(
  options?: JSZipGeneratorOptions<T>
): JSZipStreamHelper<OutputByType[T]>;

Usage Examples:

import JSZip from "jszip";

const zip = new JSZip();
zip.file("stream-test.txt", "Streaming content");

// Generate internal stream
const streamHelper = zip.generateInternalStream({
  type: "uint8array",
  compression: "DEFLATE"
});

// Use stream helper methods
streamHelper
  .on('data', (chunk, metadata) => {
    console.log(`Chunk size: ${chunk.length}`);
    console.log(`Progress: ${metadata.percent}%`);
  })
  .on('end', () => {
    console.log('Stream finished');
  })
  .on('error', (error) => {
    console.error('Stream error:', error);
  })
  .resume(); // Start the stream

// Accumulate entire result
const fullResult = await streamHelper.accumulate((metadata) => {
  console.log(`Progress: ${metadata.percent}%`);
});

Generation Options

Configure ZIP generation behavior, compression, and output format.

interface JSZipGeneratorOptions<T extends OutputType = OutputType> {
  /** Output format type */
  type?: T;
  /** Compression method for all files */
  compression?: Compression;
  /** Compression options for DEFLATE */
  compressionOptions?: CompressionOptions | null;
  /** Global comment for the ZIP file */
  comment?: string;
  /** MIME type for the generated file */
  mimeType?: string;
  /** Custom filename encoding function */
  encodeFileName?(filename: string): string;
  /** Enable streaming for individual files */
  streamFiles?: boolean;
  /** Platform type for file attributes */
  platform?: 'DOS' | 'UNIX';
}

interface CompressionOptions {
  /** Compression level (1-9) for DEFLATE */
  level: number;
}

Usage Examples:

const zip = new JSZip();
zip.file("document.txt", documentContent);

// Basic generation with compression
const result = await zip.generateAsync({
  type: "blob",
  compression: "DEFLATE",
  compressionOptions: { level: 6 }
});

// Generate with metadata
const zipWithMetadata = await zip.generateAsync({
  type: "arraybuffer",
  comment: "Generated with JSZip v3.10.1",
  mimeType: "application/zip",
  platform: "UNIX"
});

// Generate with custom filename encoding
const customEncoded = await zip.generateAsync({
  type: "base64",
  encodeFileName: (filename) => {
    // Custom encoding for special characters
    return filename.replace(/[^\x00-\x7F]/g, "_");
  }
});

// Generate with streaming enabled (better for large files)
const streamingZip = await zip.generateAsync({
  type: "nodebuffer",
  streamFiles: true,
  compression: "DEFLATE"
});

Output Types

The various output formats supported by ZIP generation.

type OutputType = keyof OutputByType;

interface OutputByType {
  base64: string;
  string: string;
  text: string;
  binarystring: string;
  array: number[];
  uint8array: Uint8Array;
  arraybuffer: ArrayBuffer;
  blob: Blob;
  nodebuffer: Buffer;
}

Usage Examples:

const zip = new JSZip();
zip.file("example.txt", "Example content");

// String outputs
const base64String = await zip.generateAsync({type: "base64"});
const binaryString = await zip.generateAsync({type: "binarystring"});
const textString = await zip.generateAsync({type: "string"});

// Binary outputs  
const uint8Array = await zip.generateAsync({type: "uint8array"});
const arrayBuffer = await zip.generateAsync({type: "arraybuffer"});
const numberArray = await zip.generateAsync({type: "array"});

// Platform-specific outputs
const blob = await zip.generateAsync({type: "blob"}); // Browser
const buffer = await zip.generateAsync({type: "nodebuffer"}); // Node.js

Progress Tracking

Monitor ZIP generation progress with detailed metadata.

interface JSZipMetadata {
  /** Completion percentage (0-100) */
  percent: number;
  /** Currently processing file path */
  currentFile: string | null;
}

type OnUpdateCallback = (metadata: JSZipMetadata) => void;

Usage Examples:

const zip = new JSZip();
// Add multiple files...

// Track progress during generation
const result = await zip.generateAsync(
  { type: "blob", compression: "DEFLATE" },
  (metadata) => {
    // Update progress bar
    updateProgressBar(metadata.percent);
    
    // Show current file
    if (metadata.currentFile) {
      console.log(`Processing: ${metadata.currentFile}`);
    }
    
    // Check if complete
    if (metadata.percent === 100) {
      console.log("ZIP generation completed!");
    }
  }
);

// Progress tracking with streaming
const stream = zip.generateNodeStream(
  { compression: "DEFLATE" },
  (metadata) => {
    document.getElementById('progress').textContent = 
      `${metadata.percent}% - ${metadata.currentFile || 'Finalizing...'}`;
  }
);

Platform Considerations

Handle platform-specific differences between browser and Node.js environments.

Browser Usage:

// Use Blob for file downloads
const blob = await zip.generateAsync({type: "blob"});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'archive.zip';
a.click();
URL.revokeObjectURL(url);

// Use ArrayBuffer for binary processing
const arrayBuffer = await zip.generateAsync({type: "arraybuffer"});
const view = new Uint8Array(arrayBuffer);

Node.js Usage:

import fs from 'fs';

// Use Buffer for file system operations
const buffer = await zip.generateAsync({type: "nodebuffer"});
fs.writeFileSync('output.zip', buffer);

// Use streams for large files
const stream = zip.generateNodeStream({streamFiles: true});
stream.pipe(fs.createWriteStream('large-archive.zip'));

docs

extraction.md

file-operations.md

generation.md

index.md

loading.md

utilities.md

tile.json