or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

archive-control.mdarchive-creation.mdcontent-operations.mdformat-options.mdindex.md
tile.json

index.mddocs/

Archiver

Archiver is a streaming interface for archive generation that supports multiple formats including ZIP, TAR, and JSON. It provides a fluent API for appending files from various sources including streams, strings, buffers, file paths, directories, and glob patterns with configurable compression levels and robust error handling.

Package Information

  • Package Name: archiver
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install archiver
  • Node.js Version: >= 14

Core Imports

const archiver = require('archiver');

Basic Usage

const fs = require('fs');
const archiver = require('archiver');

// Create a file to stream archive data to
const output = fs.createWriteStream(__dirname + '/example.zip');
const archive = archiver('zip', {
  zlib: { level: 9 } // Sets the compression level
});

// Listen for all archive data to be written
output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');
  console.log('archiver has been finalized and the output file descriptor has closed.');
});

// Good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function(err) {
  if (err.code === 'ENOENT') {
    // log warning
  } else {
    // throw error
    throw err;
  }
});

// Good practice to catch this error explicitly
archive.on('error', function(err) {
  throw err;
});

// Pipe archive data to the file
archive.pipe(output);

// Append files from various sources
archive
  .append('string content', { name: 'file.txt' })
  .file('/path/to/file.txt', { name: 'renamed.txt' })
  .directory('/path/to/dir', 'subdir')
  .finalize();

Architecture

Archiver is built around several key components:

  • Factory Functions: Main archiver() function and archiver.create() for creating archive instances
  • Format Registration: Plugin system allowing custom archive formats via archiver.registerFormat()
  • Core Archiver Class: Transform stream that handles the archiving process with methods for appending content
  • Built-in Formats: ZIP, TAR, and JSON format support with format-specific options
  • Streaming Interface: Node.js Transform stream for efficient memory usage with large files
  • Event System: Progress tracking and error handling through standard Node.js events

Capabilities

Archive Creation and Management

Core functionality for creating and managing archive instances with built-in format support.

/**
 * Creates a new Archiver instance
 * @param {string} format - Archive format ('zip', 'tar', 'json')
 * @param {Object} options - Format-specific options
 * @returns {Archiver} Archiver instance
 */
function archiver(format, options);

/**
 * Creates a new Archiver instance (alternative method)
 * @param {string} format - Archive format
 * @param {Object} options - Format-specific options
 * @returns {Archiver} Archiver instance
 */
archiver.create(format, options);

/**
 * Registers a custom archive format
 * @param {string} format - Format name
 * @param {Function} module - Format module with append and finalize methods
 */
archiver.registerFormat(format, module);

/**
 * Checks if a format is already registered
 * @param {string} format - Format name to check
 * @returns {boolean} True if format is registered
 */
archiver.isRegisteredFormat(format);

Archive Creation and Management

Content Appending Operations

Methods for adding various types of content to archives including files, directories, streams, and string data.

/**
 * Appends content to archive from Buffer, Stream, or String
 * @param {Buffer|Stream|string} source - Content source
 * @param {EntryData} data - Entry metadata
 * @returns {Archiver} This instance for chaining
 */
append(source, data);

/**
 * Appends a file from filesystem using lazy stream
 * @param {string} filepath - Path to file
 * @param {EntryData} data - Entry metadata
 * @returns {Archiver} This instance for chaining
 */
file(filepath, data);

/**
 * Recursively appends directory and its contents
 * @param {string} dirpath - Directory path
 * @param {string|false} destpath - Destination path in archive
 * @param {EntryData|Function} data - Entry metadata or filter function
 * @returns {Archiver} This instance for chaining
 */
directory(dirpath, destpath, data);

/**
 * Appends files matching glob pattern
 * @param {string} pattern - Glob pattern
 * @param {Object} options - Glob options
 * @param {EntryData} data - Entry metadata
 * @returns {Archiver} This instance for chaining
 */
glob(pattern, options, data);

/**
 * Creates symbolic link entry (programmatic, no filesystem interaction)
 * @param {string} filepath - Link path in archive
 * @param {string} target - Link target
 * @param {number} mode - File mode (optional)
 * @returns {Archiver} This instance for chaining
 */
symlink(filepath, target, mode);

Content Appending Operations

Archive Finalization and Control

Methods for controlling the archiving process including finalization, abortion, and progress tracking.

/**
 * Finalizes archive and prevents further appending
 * @returns {Promise} Resolves when archive is complete
 */
finalize();

/**
 * Aborts archiving process with best-effort cleanup
 * @returns {Archiver} This instance for chaining
 */
abort();

/**
 * Returns current byte length emitted by archive
 * @returns {number} Current byte length
 */
pointer();

Archive Finalization and Control

Format Support

Built-in Formats

  • ZIP: Compressed archive format with configurable compression levels
  • TAR: Tape archive format with optional gzip compression
  • JSON: JSON metadata format for entry information

Format-Specific Options and Features

Common Types

/**
 * Entry metadata for archive entries
 */
interface EntryData {
  /** Entry name including internal path (required) */
  name: string;
  /** Entry date, defaults to current time */
  date?: string | Date;
  /** Entry permissions (0755 for dirs, 0644 for files) */
  mode?: number;
  /** Path prefix for entry name */
  prefix?: string;
  /** Filesystem stats to avoid additional calls */
  stats?: fs.Stats;
}

/**
 * Core archiver options
 */
interface CoreOptions {
  /** Number of workers for fs.stat queue (default: 4) */
  statConcurrency?: number;
  /** Stream buffer size (default: 1MB) */
  highWaterMark?: number;
}

/**
 * Progress tracking data
 */
interface ProgressData {
  entries: {
    /** Total entries appended */
    total: number;
    /** Entries processed */
    processed: number;
  };
  fs: {
    /** Total bytes from filesystem entries */
    totalBytes: number;
    /** Processed bytes from filesystem entries */
    processedBytes: number;
  };
}

/**
 * Archiver error class with specific error codes
 */
class ArchiverError extends Error {
  /** Error code indicating the type of error */
  code: string;
  /** Additional error data */
  data?: any;
}

/**
 * Common Archiver error codes
 */
const ERROR_CODES = {
  ABORTED: 'archive was aborted',
  DIRECTORYDIRPATHREQUIRED: 'directory dirpath argument must be a non-empty string value',
  DIRECTORYFUNCTIONINVALIDDATA: 'invalid data returned by directory custom data function',
  ENTRYNAMEREQUIRED: 'entry name must be a non-empty string value',
  FILEFILEPATHREQUIRED: 'file filepath argument must be a non-empty string value',
  FINALIZING: 'archive already finalizing',
  QUEUECLOSED: 'queue closed',
  NOENDMETHOD: 'no suitable finalize/end method defined by module',
  DIRECTORYNOTSUPPORTED: 'support for directory entries not defined by module',
  FORMATSET: 'archive format already set',
  INPUTSTEAMBUFFERREQUIRED: 'input source must be valid Stream or Buffer instance',
  MODULESET: 'module already set',
  SYMLINKNOTSUPPORTED: 'support for symlink entries not defined by module',
  SYMLINKFILEPATHREQUIRED: 'symlink filepath argument must be a non-empty string value',
  SYMLINKTARGETREQUIRED: 'symlink target argument must be a non-empty string value',
  ENTRYNOTSUPPORTED: 'entry not supported'
};

Events

// Event: 'entry' - Fired when entry is processed and appended
archive.on('entry', (entryData) => { /* handle entry */ });

// Event: 'progress' - Fired with processing progress information
archive.on('progress', (progressData) => { /* track progress */ });

// Event: 'end' - Fired when archive data has been fully emitted
archive.on('end', () => { /* archive stream complete */ });

// Event: 'warning' - Fired for non-blocking errors (e.g., file not found)
archive.on('warning', (err) => { /* handle warnings */ });

// Event: 'error' - Fired for blocking errors
archive.on('error', (err) => { /* handle errors */ });