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

utilities.mddocs/

Utility and Configuration

Static properties providing feature detection, version information, configuration options, and platform compatibility utilities for JSZip.

Capabilities

Version Information

Access the current JSZip library version.

/**
 * Current version of the JSZip library
 */
static version: string;

Usage Examples:

import JSZip from "jszip";

console.log("JSZip version:", JSZip.version); // "3.10.1"

// Version-dependent feature checks
const [major, minor, patch] = JSZip.version.split('.').map(Number);
if (major >= 3 && minor >= 10) {
  console.log("Modern JSZip version with latest features");
}

// Include version in generated ZIP comments
const zip = new JSZip();
zip.file("readme.txt", "Hello World");
const result = await zip.generateAsync({
  type: "blob",
  comment: `Generated with JSZip v${JSZip.version}`
});

Feature Detection

Runtime detection of platform capabilities and supported features.

/**
 * Platform capability detection
 */
static support: JSZipSupport;

interface JSZipSupport {
  /** ArrayBuffer support */
  arraybuffer: boolean;
  /** Uint8Array support */
  uint8array: boolean;
  /** Blob support (browser) */
  blob: boolean;
  /** Node.js Buffer support */
  nodebuffer: boolean;
  /** Node.js Readable stream support */
  nodestream: boolean;
}

Usage Examples:

import JSZip from "jszip";

// Check platform capabilities
console.log("Platform support:", JSZip.support);

// Conditional logic based on support
if (JSZip.support.blob) {
  // Browser environment
  const zip = new JSZip();
  zip.file("test.txt", "Hello");
  const blob = await zip.generateAsync({type: "blob"});
  console.log("Generated as Blob");
} else if (JSZip.support.nodebuffer) {
  // Node.js environment
  const zip = new JSZip();
  zip.file("test.txt", "Hello");
  const buffer = await zip.generateAsync({type: "nodebuffer"});
  console.log("Generated as Buffer");
}

// Feature-based format selection
function getBestOutputFormat() {
  if (JSZip.support.uint8array) {
    return "uint8array";
  } else if (JSZip.support.arraybuffer) {
    return "arraybuffer";
  } else {
    return "array";
  }
}

const zip = new JSZip();
const format = getBestOutputFormat();
const result = await zip.generateAsync({type: format});

// Input format validation
function canUseInput(inputType) {
  switch (inputType) {
    case 'blob':
      return JSZip.support.blob;
    case 'nodebuffer':
      return JSZip.support.nodebuffer;
    case 'uint8array':
      return JSZip.support.uint8array;
    case 'arraybuffer':
      return JSZip.support.arraybuffer;
    default:
      return true; // string, array always supported
  }
}

Default Configuration

Access default options used for file operations.

/**
 * Default options for file operations
 */
static defaults: object;

Usage Examples:

import JSZip from "jszip";

// Inspect default settings
console.log("Default options:", JSZip.defaults);
// Typical output:
// {
//   base64: false,
//   binary: false,
//   dir: false,
//   createFolders: true,
//   date: null,
//   compression: null,
//   compressionOptions: null,
//   comment: null,
//   unixPermissions: null,
//   dosPermissions: null
// }

// Understand default behavior
const zip = new JSZip();

// These two calls are equivalent due to defaults
zip.file("text1.txt", "Hello", {}); 
zip.file("text2.txt", "Hello", {
  base64: false,
  binary: false,
  createFolders: true,
  date: null
});

// Defaults help with consistent behavior
function addTextFile(zip, path, content) {
  // Uses defaults: createFolders=true, binary=false, etc.
  return zip.file(path, content);
}

function addBinaryFile(zip, path, data) {
  // Override defaults for binary data
  return zip.file(path, data, {
    binary: true,  // Override default of false
    base64: false  // Use default
  });
}

External Dependencies

Access external library dependencies and configuration.

/**
 * External dependencies configuration
 */
static external: {
  Promise: PromiseConstructorLike;
};

Usage Examples:

import JSZip from "jszip";

// Check Promise implementation
console.log("Promise implementation:", JSZip.external.Promise);

// JSZip uses native Promise if available, or lie polyfill
const isNativePromise = JSZip.external.Promise === window.Promise || 
                       JSZip.external.Promise === global.Promise;

console.log("Using native Promise:", isNativePromise);

// Custom Promise implementation (advanced usage)
// Note: This is typically not needed as JSZip handles this automatically
if (typeof window !== 'undefined' && window.Promise) {
  // Browser with native Promise
  console.log("Browser environment with native Promise");
} else if (typeof global !== 'undefined' && global.Promise) {
  // Node.js with native Promise
  console.log("Node.js environment with native Promise");
} else {
  // Polyfilled environment
  console.log("Using Promise polyfill");
}

// All JSZip async operations use this Promise implementation
const zip = new JSZip();
zip.file("test.txt", "Hello");

// This returns JSZip.external.Promise instance
const promise = zip.generateAsync({type: "string"});
console.log("Is JSZip Promise:", promise instanceof JSZip.external.Promise);

Utility Functions

Access instance-level utility methods for ZIP manipulation.

Clone Operation

Create deep copies of JSZip instances.

/**
 * Create a deep copy of the JSZip instance
 * @returns New JSZip instance with copied files and settings
 */
clone(): JSZip;

Usage Examples:

const originalZip = new JSZip();
originalZip.file("readme.txt", "Original content");
originalZip.file("data.json", JSON.stringify({version: 1}));

// Create a copy
const clonedZip = originalZip.clone();

// Modify the clone without affecting original
clonedZip.file("readme.txt", "Modified content");
clonedZip.file("new-file.txt", "Additional content");

// Original remains unchanged
const originalContent = await originalZip.file("readme.txt").async("string");
console.log("Original:", originalContent); // "Original content"

const clonedContent = await clonedZip.file("readme.txt").async("string");
console.log("Cloned:", clonedContent); // "Modified content"

// Different use case: template ZIP
const templateZip = new JSZip();
templateZip.file("template.html", "<html>{{content}}</html>");
templateZip.file("styles.css", "body { margin: 0; }");

// Create variations from template
const userZip1 = templateZip.clone();
userZip1.file("content.txt", "User 1 content");

const userZip2 = templateZip.clone();
userZip2.file("content.txt", "User 2 content");

// Generate separate ZIP files
const zip1 = await userZip1.generateAsync({type: "blob"});
const zip2 = await userZip2.generateAsync({type: "blob"});

Platform Detection Utilities

Helper patterns for detecting and handling different JavaScript environments.

Usage Examples:

import JSZip from "jszip";

// Environment detection helper
function getEnvironment() {
  if (typeof window !== 'undefined') {
    return 'browser';
  } else if (typeof global !== 'undefined' && global.process) {
    return 'node';
  } else {
    return 'unknown';
  }
}

// Platform-appropriate file handling
async function saveZipFile(zip, filename) {
  const env = getEnvironment();
  
  if (env === 'browser') {
    // Browser: use Blob and download
    const blob = await zip.generateAsync({type: "blob"});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
    
  } else if (env === 'node') {
    // Node.js: use Buffer and fs
    const fs = require('fs');
    const buffer = await zip.generateAsync({type: "nodebuffer"});
    fs.writeFileSync(filename, buffer);
    
  } else {
    // Fallback: use array format
    const array = await zip.generateAsync({type: "array"});
    console.log("Generated ZIP as number array:", array.length, "bytes");
  }
}

// Feature-based format selection
function selectBestFormat(purpose) {
  const support = JSZip.support;
  
  switch (purpose) {
    case 'download':
      return support.blob ? 'blob' : 'arraybuffer';
      
    case 'upload':
      return support.arraybuffer ? 'arraybuffer' : 'array';
      
    case 'storage':
      return support.nodebuffer ? 'nodebuffer' : 
             support.uint8array ? 'uint8array' : 'array';
             
    case 'processing':
      return support.uint8array ? 'uint8array' : 'array';
      
    default:
      return 'string';
  }
}

// Cross-platform ZIP loading
async function loadZipFromSource(source) {
  let zipData;
  
  if (typeof source === 'string') {
    // URL or file path
    if (source.startsWith('http')) {
      // URL - use fetch
      const response = await fetch(source);
      zipData = await response.arrayBuffer();
    } else {
      // File path - Node.js only
      const fs = require('fs');
      zipData = fs.readFileSync(source);
    }
  } else if (source instanceof File) {
    // Browser File object
    zipData = await source.arrayBuffer();
  } else {
    // Direct data
    zipData = source;
  }
  
  return await JSZip.loadAsync(zipData);
}

Configuration Best Practices

Recommended patterns for configuring JSZip based on use cases.

Usage Examples:

// Web application configuration
const webConfig = {
  // Prefer blob for downloads
  outputFormat: JSZip.support.blob ? 'blob' : 'arraybuffer',
  
  // Enable compression for bandwidth
  compression: 'DEFLATE',
  compressionOptions: { level: 6 },
  
  // Browser-friendly settings
  platform: 'DOS',
  createFolders: true
};

// Node.js application configuration
const nodeConfig = {
  // Use Buffer for file system operations
  outputFormat: 'nodebuffer',
  
  // Higher compression for storage
  compression: 'DEFLATE',
  compressionOptions: { level: 9 },
  
  // Unix-style attributes
  platform: 'UNIX',
  createFolders: true
};

// Mobile/performance-optimized configuration
const mobileConfig = {
  // Faster format for mobile
  outputFormat: JSZip.support.uint8array ? 'uint8array' : 'array',
  
  // Lower compression for speed
  compression: 'DEFLATE',
  compressionOptions: { level: 1 },
  
  // Skip CRC checks for speed
  checkCRC32: false,
  streamFiles: true
};

// Apply configuration based on environment
function createOptimizedZip() {
  const zip = new JSZip();
  
  // Set appropriate defaults based on environment
  if (getEnvironment() === 'browser') {
    zip.generateConfig = webConfig;
  } else if (getEnvironment() === 'node') {
    zip.generateConfig = nodeConfig;
  } else {
    zip.generateConfig = mobileConfig;
  }
  
  return zip;
}

docs

extraction.md

file-operations.md

generation.md

index.md

loading.md

utilities.md

tile.json