CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-extract-zip

Pure JavaScript ZIP extraction library for extracting archives into directories

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

index.mddocs/

Extract Zip

Extract Zip is a pure JavaScript library for extracting ZIP archives into directories. It provides both programmatic API and command-line interface capabilities, using the yauzl ZIP parser for reliable extraction with support for custom file and directory permissions, entry-level processing hooks, and asynchronous operation patterns.

Package Information

  • Package Name: extract-zip
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install extract-zip
  • Node.js Requirement: >= 10.17.0

Core Imports

const extract = require('extract-zip');

For TypeScript:

import extract = require('extract-zip');

Basic Usage

const extract = require('extract-zip');

async function extractZip() {
  try {
    await extract('/path/to/archive.zip', { dir: '/path/to/destination' });
    console.log('Extraction complete');
  } catch (err) {
    console.error('Extraction failed:', err);
  }
}

Architecture

Extract Zip is built around several key components:

  • Main Function: The default export provides a simple async interface for ZIP extraction
  • Extractor Class: Internal class that handles the extraction logic using yauzl
  • Security: Path traversal protection prevents zip slip vulnerabilities
  • Permissions: Support for custom file and directory permissions with sensible defaults
  • Entry Processing: Configurable hooks for processing individual ZIP entries

Capabilities

ZIP Extraction

Main extraction function that extracts a ZIP archive to a specified directory.

/**
 * Extract a ZIP archive to a directory
 * @param zipPath - Path to the ZIP file to extract
 * @param opts - Extraction options
 * @returns Promise that resolves when extraction is complete
 */
async function extract(zipPath: string, opts: Options): Promise<void>;

Extraction Options

Configuration options for controlling the extraction process.

interface Options {
  /** Target directory path (required, must be absolute) */
  dir: string;
  /** Default directory permissions (defaults to 0o755) */
  defaultDirMode?: number;
  /** Default file permissions (defaults to 0o644) */
  defaultFileMode?: number;
  /** Callback for each ZIP entry during extraction */
  onEntry?: (entry: Entry, zipfile: ZipFile) => void;
}

Entry Processing Callback

Optional callback function that receives each ZIP entry during extraction, allowing for custom processing or progress tracking.

/**
 * Callback function called for each ZIP entry
 * @param entry - yauzl Entry object representing the current ZIP entry
 * @param zipfile - yauzl ZipFile object representing the opened ZIP file
 */
type OnEntryCallback = (entry: Entry, zipfile: ZipFile) => void;

Command Line Interface

The package includes a CLI tool for extracting ZIP files from the command line.

# Extract ZIP to current directory
extract-zip foo.zip

# Extract ZIP to specific directory  
extract-zip foo.zip <targetDirectory>

Types

import { Entry, ZipFile } from 'yauzl';

interface Options {
  dir: string;
  defaultDirMode?: number;
  defaultFileMode?: number;
  onEntry?: (entry: Entry, zipfile: ZipFile) => void;
}

Usage Examples

Basic Extraction

const extract = require('extract-zip');

async function main() {
  await extract('my-archive.zip', { dir: '/tmp/extracted' });
}

Custom Permissions

const extract = require('extract-zip');

async function main() {
  await extract('my-archive.zip', {
    dir: '/tmp/extracted',
    defaultDirMode: 0o755,
    defaultFileMode: 0o644
  });
}

Entry Processing

const extract = require('extract-zip');

async function main() {
  await extract('my-archive.zip', {
    dir: '/tmp/extracted',
    onEntry: (entry, zipfile) => {
      console.log(`Extracting: ${entry.fileName}`);
    }
  });
}

TypeScript Usage

import extract = require('extract-zip');

async function extractWithTypes(): Promise<void> {
  const options: extract.Options = {
    dir: '/tmp/extracted',
    defaultDirMode: 0o755,
    onEntry: (entry, zipfile) => {
      console.log(`Processing: ${entry.fileName}`);
    }
  };
  
  await extract('archive.zip', options);
}

Error Handling

The library throws errors in several scenarios:

  • Invalid target directory: When the target directory path is not absolute (exact message: "Target directory is expected to be absolute")
  • ZIP parsing errors: When the ZIP file is corrupted or invalid
  • Path traversal attempts: When ZIP entries attempt to write outside the target directory (format: "Out of bound path "{path}" found while processing file {fileName}")
  • File system errors: When directory creation or file writing fails
  • CLI usage errors: When CLI is called without arguments, shows "Usage: extract-zip foo.zip <targetDirectory>" and exits
const extract = require('extract-zip');

async function safeExtract() {
  try {
    await extract('archive.zip', { dir: '/absolute/path/to/destination' });
  } catch (error) {
    if (error.message.includes('Out of bound path')) {
      console.error('Security error: ZIP contains path traversal attempt');
    } else if (error.message === 'Target directory is expected to be absolute') {
      console.error('Invalid target directory: must be absolute path');
    } else {
      console.error('Extraction failed:', error.message);
    }
  }
}

// CLI error handling (when using extract-zip command)
// CLI errors are prefixed with "error!" and cause process.exit(1)

Security Features

  • Path Traversal Protection: Automatically prevents zip slip vulnerabilities by validating extracted file paths
  • Symlink Handling: Safely handles symbolic links within ZIP archives
  • macOS Metadata Filtering: Automatically skips __MACOSX/ metadata entries
  • Permission Validation: Safely applies file and directory permissions from ZIP entries

Path Handling

The library automatically handles path normalization and directory creation:

  • Target directory normalization: Uses fs.realpath() to resolve the target directory to its canonical path
  • Recursive directory creation: Automatically creates all necessary parent directories
  • Path validation: Checks that extracted files don't escape the target directory using relative path validation
  • Cross-platform compatibility: Handles both Unix and Windows path separators and directory structures

docs

index.md

tile.json