A streaming interface for archive generation supporting ZIP, TAR, and JSON formats
npx @tessl/cli install tessl/npm-archiver@7.0.0Archiver 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.
npm install archiverconst archiver = require('archiver');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();Archiver is built around several key components:
archiver() function and archiver.create() for creating archive instancesarchiver.registerFormat()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
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);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-Specific Options and Features
/**
* 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'
};// 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 */ });