### Basic TAR Creation Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md Demonstrates how to create a basic uncompressed TAR archive using TarArchive. ```APIDOC ## Basic TAR Creation Example ```javascript import fs from 'fs'; import { TarArchive } from 'archiver'; const output = fs.createWriteStream('archive.tar'); const archive = new TarArchive(); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); ``` ``` -------------------------------- ### Install Archiver.js Source: https://github.com/archiverjs/node-archiver/blob/master/README.md Install the Archiver.js package using npm. ```bash npm install archiver --save ``` -------------------------------- ### Directory Entry Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Illustrates how to define a directory entry, noting that a trailing '/' is added automatically. ```javascript { name: 'folder', type: 'directory', mode: 0o755 } ``` -------------------------------- ### Complete Entry Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Shows all possible properties for an EntryData object, including optional fields. ```javascript { name: 'documents/file.txt', type: 'file', date: new Date('2024-01-01'), mode: 0o644, prefix: null, sourcePath: '/home/user/file.txt', stats: fsStatsObject } ``` -------------------------------- ### Minimal Entry Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Demonstrates the minimum required properties for an EntryData object. ```javascript { name: 'file.txt' } ``` -------------------------------- ### TarArchive Examples with Gzip Configuration Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Demonstrates creating Tar archives with different gzip compression levels and memory settings for various use cases. ```javascript import { TarArchive } from 'archiver'; // Plain TAR (uncompressed, fast) const archive = new TarArchive({ gzip: false }); ``` ```javascript // Compressed TAR.GZ (standard) const archive = new TarArchive({ gzip: true, gzipOptions: { level: 6 } }); ``` ```javascript // Highly compressed TAR.GZ (slow, best compression) const archive = new TarArchive({ gzip: true, gzipOptions: { level: 9, memLevel: 9 } }); ``` ```javascript // Fast TAR.GZ for large files const archive = new TarArchive({ gzip: true, gzipOptions: { level: 1, memLevel: 7 } }); ``` -------------------------------- ### Archiver TAR Entry Examples Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Demonstrates how to append TAR entries with custom timestamps and create symlink entries. ```javascript // TAR entries with timestamps (normalized to seconds) archive.append(data, { name: 'file.txt', date: new Date('2024-01-01T12:00:00Z') // Seconds precision in TAR }) // Symlink entry (auto-set linkname internally) archive.symlink('link.txt', 'target.txt') ``` -------------------------------- ### Entry Data Configuration Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure individual entry behavior when appending to an archive, such as name, type, and metadata. ```javascript archive.append(source, { name: 'filename.txt', type: 'file', date: new Date(), mode: 0o644, prefix: null, stats: fsStats, callback: undefined }) ``` -------------------------------- ### Backup Directories with Permissions Preserved Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md This example demonstrates creating a gzip-compressed TAR archive while preserving file permissions and ownership from the filesystem. This is crucial for system backups or configuration deployments. ```javascript const archive = new TarArchive({ gzip: true }); archive.pipe(fs.createWriteStream('backup.tar.gz')); // Permissions and ownership from filesystem are preserved archive.directory('/etc/myapp', 'config'); archive.directory('/var/data', 'data'); archive.finalize(); ``` -------------------------------- ### Create a Basic TAR Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md This snippet demonstrates how to create a simple TAR archive by appending files and directories. Ensure you have the 'archiver' and 'fs' modules installed. ```javascript import fs from 'fs'; import { TarArchive } from 'archiver'; const output = fs.createWriteStream('archive.tar'); const archive = new TarArchive(); archive.pipe(output); archive.append('Hello World', { name: 'hello.txt' }); archive.file('input.txt', { name: 'renamed.txt' }); archive.finalize(); ``` -------------------------------- ### Compressed TAR (TAR.GZ) Creation Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md Shows how to create a gzip-compressed TAR archive (.tar.gz) with custom gzip compression level. ```APIDOC ## Compressed TAR (TAR.GZ) Creation Example ```javascript const output = fs.createWriteStream('archive.tar.gz'); const archive = new TarArchive({ gzip: true, gzipOptions: { level: 9 } }); archive.pipe(output); archive.directory('./data', 'data'); await archive.finalize(); ``` ``` -------------------------------- ### Create a Zip Archive Source: https://github.com/archiverjs/node-archiver/blob/master/website/docs/quickstart.md This example demonstrates how to create a zip archive by appending files from streams, strings, buffers, and glob patterns. It includes error handling and event listeners for archive creation. ```javascript // require modules 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 // 'close' event is fired only when a file descriptor is involved output.on("close", function () { console.log(archive.pointer() + " total bytes"); console.log( "archiver has been finalized and the output file descriptor has closed." ); }); // This event is fired when the data source is drained no matter what was the data source. // It is not part of this library but rather from the NodeJS Stream API. // @see: https://nodejs.org/api/stream.html#stream_event_end output.on("end", function () { console.log("Data has been drained"); }); // 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 a file from stream const file1 = __dirname + "/file1.txt"; archive.append(fs.createReadStream(file1), { name: "file1.txt" }); // append a file from string archive.append("string cheese!", { name: "file2.txt" }); // append a file from buffer const buffer3 = Buffer.from("buff it!"); archive.append(buffer3, { name: "file3.txt" }); // append a file archive.file("file1.txt", { name: "file4.txt" }); // append files from a sub-directory and naming it `new-subdir` within the archive archive.directory("subdir/", "new-subdir"); // append files from a sub-directory, putting its contents at the root of archive archive.directory("subdir/", false); // append files from a glob pattern archive.glob("file*.txt", { cwd: __dirname }); // finalize the archive (ie we are done appending files but streams have to finish yet) // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand archive.finalize(); ``` -------------------------------- ### Directory Append with Stat Queue Flow Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/advanced-topics.md Demonstrates the data flow for appending a directory, including the use of a separate queue for file system statistics. Shows how stat results are used to create appropriate sources for files and directories. ```text User: archive.directory('./src', 'src') ↓ directory() validates path ↓ _pending++ (now 1) ↓ readdirGlob('./src') starts ↓ (for each matched file) ↓ globber pauses ↓ _append(match.absolute, entryData) ↓ _entriesCount++ ↓ _statQueue.push(task) (because no stats in data yet) ↓ (when stat queue processes) ↓ _onStatQueueTask(task, cb) ↓ fs.lstat(filepath) called ↓ _updateQueueTaskWithStats(task, stats) ↓ Creates appropriate source (lazy stream for files, buffer for dirs) ↓ _queue.push(updated task) ↓ (continues as in append flow above) ``` -------------------------------- ### Stream-Based TAR Creation to Standard Output Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md This example demonstrates creating a gzip-compressed TAR archive and piping it directly to standard output. This is efficient for piping archives to other processes or network streams. ```javascript import { TarArchive } from 'archiver'; import fs from 'fs'; const archive = new TarArchive({ gzip: true }); // Pipe to stdout or HTTP response archive.pipe(process.stdout); archive.file('/path/to/file1.txt', { name: 'file1.txt' }); archive.file('/path/to/file2.txt', { name: 'file2.txt' }); await archive.finalize(); ``` -------------------------------- ### Archiver Progress Event Listener Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md An example of how to listen for the 'progress' event and log the archiving progress in terms of percentage and entry counts. ```javascript archive.on('progress', (progress) => { const percent = (progress.fs.processedBytes / progress.fs.totalBytes) * 100; console.log(`Progress: ${percent.toFixed(1)}%`); console.log(`Entries: ${progress.entries.processed}/${progress.entries.total}`); }); ``` -------------------------------- ### AWS S3 Upload Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Create a gzipped Tar archive and stream it directly to an AWS S3 bucket. This example requires prior setup for S3 upload stream. ```javascript const archive = new TarArchive({ gzip: true }); const s3Stream = uploadToS3('backup.tar.gz'); archive.pipe(s3Stream); archive.directory('./data'); await archive.finalize(); ``` -------------------------------- ### Simple Append Flow Example Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/advanced-topics.md Illustrates the data flow when a user appends a simple string source to the archive. Shows input validation, source normalization, queueing, module processing, and event emission. ```text User: archive.append('hello', { name: 'file.txt' }) ↓ append() validates input ↓ normalizeInputSource() converts string to Buffer ↓ _entriesCount++ (now 1) ↓ _queue.push({ source: Buffer, data: {...} }) ↓ (when queue processes) ↓ _onQueueTask() called ↓ _moduleAppend(source, data, callback) ↓ module.append(source, data, callback) ↓ module writes to engine ↓ callback() ↓ emit 'entry' event with data ↓ _entriesProcessedCount++ (now 1) ↓ emit 'progress' event ``` -------------------------------- ### Create a Compressed TAR.GZ Archive with Maximum Compression Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md This example shows how to create a gzip-compressed TAR archive (tar.gz) with the highest compression level. This is useful for minimizing file size at the cost of longer compression time. ```javascript const output = fs.createWriteStream('archive.tar.gz'); const archive = new TarArchive({ gzip: true, gzipOptions: { level: 9 } // Maximum compression }); archive.pipe(output); archive.directory('/path/to/files', 'backup'); await archive.finalize(); ``` -------------------------------- ### Basic JSON Archive Creation Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Demonstrates how to create a basic JSON archive. The output is a JSON array of file objects, each containing metadata and checksums. Ensure 'archiver' is installed and imported correctly. ```javascript import fs from 'fs'; import { JsonArchive } from 'archiver'; const output = fs.createWriteStream('archive.json'); const archive = new JsonArchive(); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); // Result is a JSON array of file objects ``` -------------------------------- ### Directory Entry Example in JSON Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Shows the JSON structure for a directory entry in an archive manifest. Key fields include type, name, and size (which is 0 for directories). ```json { "type": "directory", "name": "folder/", "date": "2024-01-15T10:30:45.123Z", "mode": 493, "prefix": null, "sourcePath": "/home/user/folder/", "stats": false, "sourceType": "buffer", "size": 0, "crc32": 0 } ``` -------------------------------- ### File Entry Example in JSON Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Illustrates the structure of a file entry within a JSON archive manifest. It includes details like type, name, size, and CRC32 checksum. ```json { "type": "file", "name": "document.txt", "date": "2024-01-15T10:30:45.123Z", "mode": 420, "prefix": null, "sourcePath": "/home/user/document.txt", "stats": false, "sourceType": "stream", "size": 2048, "crc32": 3735928559 } ``` -------------------------------- ### Quick Start: Create a Zip Archive Source: https://github.com/archiverjs/node-archiver/blob/master/README.md This snippet demonstrates how to create a zip archive using Archiver.js. It shows how to append files from streams, strings, buffers, and directories, as well as using glob patterns. Ensure you have the necessary files and directories set up before running. ```javascript import fs from "fs"; import { ZipArchive } from "archiver"; // create a file to stream archive data to. const output = fs.createWriteStream(__dirname + "/example.zip"); const archive = new ZipArchive({ zlib: { level: 9 }, // Sets the compression level. }); // listen for all archive data to be written // 'close' event is fired only when a file descriptor is involved output.on("close", function () { console.log(archive.pointer() + " total bytes"); console.log( "archiver has been finalized and the output file descriptor has closed." ); }); // This event is fired when the data source is drained no matter what was the data source. // It is not part of this library but rather from the NodeJS Stream API. // @see: https://nodejs.org/api/stream.html#stream_event_end output.on("end", function () { console.log("Data has been drained"); }); // 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 a file from stream const file1 = __dirname + "/file1.txt"; archive.append(fs.createReadStream(file1), { name: "file1.txt" }); // append a file from string archive.append("string cheese!", { name: "file2.txt" }); // append a file from buffer const buffer3 = Buffer.from("buff it!"); archive.append(buffer3, { name: "file3.txt" }); // append a file archive.file("file1.txt", { name: "file4.txt" }); // append files from a sub-directory and naming it `new-subdir` within the archive archive.directory("subdir/", "new-subdir"); // append files from a sub-directory, putting its contents at the root of archive archive.directory("subdir/", false); // append files from a glob pattern archive.glob("file*.txt", { cwd: __dirname }); // finalize the archive (ie we are done appending files but streams have to finish yet) // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand archive.finalize(); ``` -------------------------------- ### Basic ZIP Creation Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Creates a basic ZIP archive with a single file. Ensure 'archiver' is installed and imported. The archive is piped to a write stream and finalized asynchronously. ```javascript import fs from 'fs'; import { ZipArchive } from 'archiver'; const output = fs.createWriteStream('archive.zip'); const archive = new ZipArchive({ zlib: { level: 9 } // Maximum compression }); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); ``` -------------------------------- ### Streaming to Database Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Create a JSON archive and stream its contents to be parsed and saved into a database. This example assumes a 'database' object with a 'save' method. ```javascript const archive = new JsonArchive(); const manifestBuffer = []; archive.on('data', (chunk) => { manifestBuffer.push(chunk); }); archive.on('end', () => { const manifest = JSON.parse(Buffer.concat(manifestBuffer)); database.save('manifest', manifest); }); archive.directory('./files'); await archive.finalize(); ``` -------------------------------- ### Trigger ENTRYNOTSUPPORTED Error Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Shows examples that trigger the ENTRYNOTSUPPORTED error. This includes appending an entry with an invalid type like 'hardlink' or attempting to append special filesystem files such as '/dev/null'. ```javascript // Invalid entry type archive.append('data', { name: 'file.txt', type: 'hardlink' }); // When encountering special filesystem file archive.file('/dev/null'); // Special device file ``` -------------------------------- ### Setup Output Stream Handlers Before Finalizing Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/advanced-topics.md Attach event listeners, such as the 'close' event for the output stream, before calling `finalize()`. This ensures that all stream events are captured correctly. ```javascript // RIGHT: Setup before finalize const output = fs.createWriteStream('archive.zip'); output.on('close', () => console.log('Closed')); const archive = new ZipArchive(); archive.pipe(output); archive.finalize(); ``` -------------------------------- ### Symlink Entry Example in JSON Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Details the JSON format for a symbolic link entry within an archive manifest. It includes the link's name and the target path ('linkname'). ```json { "type": "symlink", "name": "link.txt", "date": "2024-01-15T10:30:45.123Z", "mode": 420, "prefix": null, "sourcePath": null, "stats": false, "sourceType": "buffer", "linkname": "target.txt", "size": 0, "crc32": 0 } ``` -------------------------------- ### Handle DIRECTORYNOTSUPPORTED Error Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Listen for the 'error' event to catch DIRECTORYNOTSUPPORTED errors, which occur when attempting to add directories to archive formats that do not support them, such as JSON archives. This example shows how to log the error and suggests fallback strategies. ```javascript archive.on('error', (err) => { if (err.code === 'DIRECTORYNOTSUPPORTED') { console.error('This archive format does not support directories'); // Fall back to flat file structure or switch format } }); ``` -------------------------------- ### Initialize ZipArchive with Base Options Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure core streaming and queuing behavior for the Archiver. Adjust `statConcurrency` for parallelism in file system operations and `highWaterMark` to manage buffer size for memory and throughput. ```javascript new ZipArchive({ statConcurrency: 4, highWaterMark: 1024 * 1024 }) ``` ```javascript import { ZipArchive } from 'archiver'; // Fast archiving with more concurrency const archive = new ZipArchive({ statConcurrency: 8, highWaterMark: 4 * 1024 * 1024 // 4 MB buffer }); ``` ```javascript import { ZipArchive } from 'archiver'; // Memory-constrained environment const archive = new ZipArchive({ statConcurrency: 2, highWaterMark: 256 * 1024 // 256 KB buffer }); ``` -------------------------------- ### Get Current Emitted Length Source: https://github.com/archiverjs/node-archiver/blob/master/website/docs/archiver_api.md Returns the current length in bytes that has been emitted by the archiver. ```javascript pointer(); ``` -------------------------------- ### Get Bytes Written Source: https://github.com/archiverjs/node-archiver/blob/master/website/src/pages/zipstream.md Retrieves the total number of bytes written to the zip archive so far. ```javascript getBytesWritten() ``` -------------------------------- ### Create Basic ZIP Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Demonstrates how to create a simple ZIP archive by piping the output to a file stream and appending files with specified names. ```javascript import fs from 'fs'; import { ZipArchive } from 'archiver'; const output = fs.createWriteStream('archive.zip'); const archive = new ZipArchive(); archive.pipe(output); archive.append('Hello World', { name: 'hello.txt' }); archive.file('input.txt', { name: 'renamed.txt' }); archive.finalize(); ``` -------------------------------- ### Handling FILEFILEPATHREQUIRED Error Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Provides an example of handling the FILEFILEPATHREQUIRED error, which is emitted when an invalid file path is provided to the file() method. ```javascript archive.on('error', (err) => { if (err.code === 'FILEFILEPATHREQUIRED') { console.error('Must provide valid file path as string'); } }); ``` -------------------------------- ### Triggering FILEFILEPATHREQUIRED Error Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Shows examples that trigger the FILEFILEPATHREQUIRED error, including calling archive.file() with missing, empty, or non-string filepath arguments. ```javascript archive.file(''); // Empty string archive.file(null); // Not a string archive.file(undefined); // Missing archive.file(123); // Wrong type ``` -------------------------------- ### Best Practice: Use Reasonable Defaults Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Leverage default configurations for most use cases. Override only when specific optimizations are required, such as fast compression or large buffers. ```javascript // Most use cases work well with defaults const archive = new ZipArchive(); // Only override for specific optimization needs const fastArchive = new ZipArchive({ zlib: { level: 1 }, // Fast compression highWaterMark: 8 * 1024 * 1024 }); ``` -------------------------------- ### Handling Invalid Symlink Filepath Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Catch errors when symlink() is called with a filepath that is missing, empty, or not a string. This example shows how to detect the SYMLINKFILEPATHREQUIRED error. ```javascript archive.symlink('', 'target.txt'); // Empty filepath archive.symlink(null, 'target.txt'); // Not a string archive.symlink(undefined, 'target.txt'); // Missing ``` ```javascript archive.on('error', (err) => { if (err.code === 'SYMLINKFILEPATHREQUIRED') { console.error('Symlink must have valid path'); } }); ``` -------------------------------- ### Best Practice: Match Configuration to Use Case (Code & Media) Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure archives based on the type of files being archived. Use high compression and concurrency for code, and store mode for pre-compressed media. ```javascript // Archiving source code (many small files, very compressible) const codeArchive = new ZipArchive({ statConcurrency: 8, zlib: { level: 9 } }); // Archiving media files (large, pre-compressed) const mediaArchive = new ZipArchive({ store: true, // No compression needed statConcurrency: 4, highWaterMark: 8 * 1024 * 1024 }); ``` -------------------------------- ### Get Current Byte Pointer Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/archiver.md Call pointer() to retrieve the total number of bytes emitted to the destination stream. This is useful for determining the archive size after completion. ```javascript const archive = new ZipArchive(); const output = fs.createWriteStream('archive.zip'); archive.pipe(output); archive.append('data', { name: 'file.txt' }); output.on('close', () => { const totalBytes = archive.pointer(); console.log(`Archive size: ${totalBytes} bytes`); }); archive.finalize(); ``` -------------------------------- ### Create ZIP Archive with Directory Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Shows how to include an entire directory from the file system into the ZIP archive, preserving its structure under a specified name within the archive. ```javascript const archive = new ZipArchive(); archive.pipe(fs.createWriteStream('backup.zip')); archive.directory('/path/to/files', 'folder-in-archive'); archive.finalize(); ``` -------------------------------- ### Best Practice: Document Custom Configurations Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Document custom archive configurations with clear comments explaining the rationale behind the chosen options. This improves maintainability. ```javascript // Archive configuration for large backup const BACKUP_ARCHIVE_OPTIONS = { highWaterMark: 4 * 1024 * 1024, // 4 MB for throughput statConcurrency: 4, // Balanced parallelism zlib: { level: 6, // Default compression memLevel: 8 } }; ``` -------------------------------- ### Best Practice: Validate Configuration Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Implement validation logic for configuration options to prevent errors. Check bounds for compression levels and buffer sizes. ```javascript function createArchive(options = {}) { // Validate options if (options.highWaterMark && options.highWaterMark < 16384) { throw new Error('highWaterMark too small'); } if (options.zlib?.level && (options.zlib.level < 0 || options.zlib.level > 9)) { throw new Error('Invalid compression level'); } return new ZipArchive(options); } ``` -------------------------------- ### Initialize ZipArchive with ZIP Specific Options Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure ZIP format-specific settings such as archive comments, timestamp handling, ZIP64 support, path formatting, and default compression methods. The `zlib` option allows detailed control over the compression algorithm. ```javascript new ZipArchive({ comment: '', forceLocalTime: false, forceZip64: false, namePrependSlash: false, store: false, zlib: {} }) ``` ```javascript import { ZipArchive } from 'archiver'; // Maximum compression (slow) const archive = new ZipArchive({ zlib: { level: 9, memLevel: 9 } }); ``` ```javascript import { ZipArchive } from 'archiver'; // Fast compression (good for large files) const archive = new ZipArchive({ zlib: { level: 1, memLevel: 8 } }); ``` ```javascript import { ZipArchive } from 'archiver'; // No compression for pre-compressed data const archive = new ZipArchive({ store: true }); ``` ```javascript import { ZipArchive } from 'archiver'; // Archive with comment const archive = new ZipArchive({ comment: 'Backup created ' + new Date().toISOString() }); ``` -------------------------------- ### Archiver.js _modulePipe Method Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/advanced-topics.md Pipes the format module's output to the Archiver stream, including error handling. This setup ensures that data flows correctly and errors are caught. ```javascript _modulePipe() { // ... (implementation details) } ``` -------------------------------- ### Listen for Entry Processing Event Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/archiver.md Use archive.on('entry', ...) to log the name of each file, directory, or symlink as it is processed and appended to the archive. ```javascript archive.on('entry', (entry) => { console.log(`Appended: ${entry.name}`); }); ``` -------------------------------- ### Create ZIP with Mixed Compression Levels Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Demonstrates how to apply different compression levels, including storing files without compression, on a per-entry basis within the same ZIP archive. ```javascript const archive = new ZipArchive({ zlib: { level: 6 } }); archive.pipe(fs.createWriteStream('archive.zip')); // Use default compression (level 6) archive.append('data1', { name: 'data1.txt' }); // Store without compression archive.append(largeData, { name: 'large.bin', store: true }); // Override for specific entry archive.append('data3', { name: 'data3.txt', store: false }); archive.finalize(); ``` -------------------------------- ### Create a TAR Archive with Fast Compression Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md This snippet illustrates creating a gzip-compressed TAR archive using a low compression level for faster archiving. This is suitable when speed is prioritized over file size reduction. ```javascript const archive = new TarArchive({ gzip: true, gzipOptions: { level: 1 // Fast compression (low ratio) } }); archive.pipe(fs.createWriteStream('fast.tar.gz')); archive.glob('*.txt', { cwd: './data' }); archive.finalize(); ``` -------------------------------- ### Configure for Fast Compression (Tar Archive) Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Enable gzip compression with a low compression level for speed. This is suitable when compression time is critical. ```javascript const archive = new TarArchive({ gzip: true, gzipOptions: { level: 1, // Minimal compression memLevel: 8 } }); ``` -------------------------------- ### Handling Invalid Directory Callback Return Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Catch errors when the callback function provided to directory() returns an invalid data type (not an object or false). This example shows how to detect the DIRECTORYFUNCTIONINVALIDDATA error. ```javascript archive.directory('./src', 'src', (entry) => { if (entry.name.includes('test')) { return false; // OK: skip entry } return "invalid"; // Error: invalid return type }); ``` ```javascript archive.on('error', (err) => { if (err.code === 'DIRECTORYFUNCTIONINVALIDDATA') { console.error('Directory callback must return object or false'); } }); ``` -------------------------------- ### Handling Multiple Finalize Calls Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Prevent errors when finalize() is called multiple times concurrently. This example demonstrates catching the FINALIZING error and suggests a prevention strategy by reusing the promise or waiting for completion. ```javascript const archive = new ZipArchive(); archive.pipe(fs.createWriteStream('archive.zip')); // Multiple finalize calls const p1 = archive.finalize(); const p2 = archive.finalize(); // Error: FINALIZING ``` ```javascript archive.on('error', (err) => { if (err.code === 'FINALIZING') { console.error('finalize() already in progress'); } }); // Prevention: finalize only once const promise = archive.finalize(); // Reuse same promise or wait for completion before finalizing again ``` -------------------------------- ### Create ZIP with Custom Compression Level Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Illustrates how to configure the ZIP archive to use a specific zlib compression level, allowing for faster compression at the cost of a larger file size. ```javascript const archive = new ZipArchive({ zlib: { level: 1 // Fast compression (low compression ratio) } }); archive.pipe(fs.createWriteStream('fast.zip')); archive.glob('**/*.txt', { cwd: './data' }); archive.finalize(); ``` -------------------------------- ### TarArchive Constructor Options Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure Tar archive creation with options for gzip compression and its specific settings. ```javascript new TarArchive({ gzip: false, gzipOptions: {} }) ``` -------------------------------- ### Handle QUEUECLOSED Error Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Listen for the 'error' event to catch QUEUECLOSED errors, which occur when attempting to append data after finalize() or abort() has been called. This example logs the error indicating that the archive queue is closed. ```javascript archive.on('error', (err) => { if (err.code === 'QUEUECLOSED') { console.error('Cannot append to archive after finalize()'); } }); ``` -------------------------------- ### TarOptions Configuration Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Configure TAR archive creation with options for gzip compression and zlib settings. ```javascript { gzip?: boolean, gzipOptions?: object } ``` ```javascript new TarArchive({ gzip: true, gzipOptions: { level: 9 } }) ``` -------------------------------- ### Configure Entries Per Directory Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Use the directory() method to apply specific configurations to entries within a directory. This allows conditional compression or skipping entries. ```javascript archive.directory('./src', 'src', (entry) => { // Modify entry configuration if (entry.name.endsWith('.js')) { entry.compress = true; // Force compress (if supported) } if (entry.name.includes('node_modules')) { return false; // Skip this entry } return entry; }); ``` -------------------------------- ### Create Manifest with Checksum Verification Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Generates a JSON manifest and then reads it back to verify integrity by logging entry details. It demonstrates adding multiple files and parsing the manifest. ```javascript import crypto from 'crypto'; import fs from 'fs'; import { JsonArchive } from 'archiver'; const archive = new JsonArchive(); const output = fs.createWriteStream('manifest.json'); archive.pipe(output); // Add multiple files for (const file of ['file1.txt', 'file2.txt', 'file3.txt']) { archive.file(`./data/${file}`, { name: file }); } archive.on('end', () => { // Parse the generated JSON to verify integrity const manifest = JSON.parse(fs.readFileSync('manifest.json', 'utf-8')); console.log('Archive manifest created:'); manifest.forEach(entry => { const sizeKb = (entry.size / 1024).toFixed(2); console.log(` ${entry.name}: ${sizeKb} KB (CRC32: 0x${entry.crc32.toString(16)})`); }); }); await archive.finalize(); ``` -------------------------------- ### Configure for Memory-Constrained Environments Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Reduce highWaterMark and statConcurrency to minimize memory usage. Use a default zlib level for balanced compression and memory. ```javascript const archive = new ZipArchive({ highWaterMark: 256 * 1024, // 256 KB buffer statConcurrency: 2, // Fewer parallel operations zlib: { level: 6, // Default compression memLevel: 7 // Reduced memory } }); ``` -------------------------------- ### ZipArchive Configuration Options Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Configure ZipArchive with options for comments, compression, buffer size, and concurrency. ```javascript { comment: '', // Archive comment forceLocalTime: false, // Use local time forceZip64: false, // Force ZIP64 headers namePrependSlash: false, // Prepend "/" to paths store: false, // No compression by default zlib: { level: 6, // 0-9 compression level memLevel: 8, // Memory usage strategy: 0 // Compression strategy }, highWaterMark: 1048576, // Buffer size statConcurrency: 4 // Stat workers } ``` -------------------------------- ### ZipStream Constructor Source: https://github.com/archiverjs/node-archiver/blob/master/website/src/pages/zipstream.md Initializes a new ZipStream instance. The constructor accepts an optional options object to configure the archive's behavior, such as setting a comment, controlling time formats, enabling ZIP64 headers, or passing specific zlib compression options. ```APIDOC ## ZipStream Constructor ### Description Initializes a new ZipStream instance. The constructor accepts an optional options object to configure the archive's behavior, such as setting a comment, controlling time formats, enabling ZIP64 headers, or passing specific zlib compression options. ### Method `new ZipStream(options)` ### Parameters #### Options Object - **comment** (String) - Optional - Sets the zip archive comment. - **forceLocalTime** (Boolean) - Optional - Forces the archive to contain local file times instead of UTC. - **forceZip64** (Boolean) - Optional - Forces the archive to contain ZIP64 headers. - **namePrependSlash** (Boolean) - Optional - Prepends a forward slash to archive file paths. - **store** (Boolean) - Optional - Sets the compression method to STORE. - **zlib** (Object) - Optional - Passed to zlib to control compression. ``` -------------------------------- ### Create a Compressed TAR Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Use TarArchive with gzip enabled to create a compressed TAR.GZ file. Append directories using the 'directory' method. ```javascript import { TarArchive } from 'archiver'; const output = fs.createWriteStream('archive.tar.gz'); const archive = new TarArchive({ gzip: true, gzipOptions: { level: 9 } }); archive.pipe(output); archive.directory('./src', 'src'); await archive.finalize(); ``` -------------------------------- ### Import Archiver Classes Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Import the necessary classes for creating different archive formats. ```javascript import { Archiver, // Base class (don't instantiate directly) ZipArchive, // ZIP format archives TarArchive, // TAR/TAR.GZ format archives JsonArchive // JSON manifest archives } from 'archiver'; ``` -------------------------------- ### JsonArchive Constructor Options Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Configure Json archive creation with options for stream buffer size and file stat concurrency. ```javascript new JsonArchive({ highWaterMark: 1024 * 1024, statConcurrency: 4 }) ``` -------------------------------- ### ZipArchive Constructor Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/zip-archive.md Initializes a new ZipArchive instance. It accepts an optional ZipOptions object for configuring ZIP-specific and stream settings. ```APIDOC ## constructor(options) ### Description Initializes a new ZipArchive instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (ZipOptions) - Optional - ZIP-specific and stream configuration options. Defaults to {}. **ZipOptions:** - **comment** (string) - Optional - ZIP archive comment (metadata). Defaults to "". - **forceLocalTime** (boolean) - Optional - Use local file times instead of UTC. Defaults to false. - **forceZip64** (boolean) - Optional - Force ZIP64 headers even for small archives. Defaults to false. - **namePrependSlash** (boolean) - Optional - Prepend forward slash to all entry paths. Defaults to false. - **store** (boolean) - Optional - Use STORE compression method (no compression) instead of DEFLATE. Defaults to false. - **zlib** (object) - Optional - Options passed to Node.js zlib module for compression. Defaults to {}. - **level** (number) - Optional - Compression level (0-9, where 0=store, 9=best compression). Defaults to 6. - **memLevel** (number) - Optional - Memory allocation level (1-9). Defaults to 8. - **strategy** (number) - Optional - Compression strategy (0=default, 1=filtered, 2=huffman, 3=RLE, 4=fixed). Defaults to 0. - **highWaterMark** (number) - Optional - Maximum bytes in internal buffer. Defaults to 1048576. - **statConcurrency** (number) - Optional - Concurrent file stat operations. Defaults to 4. ### Return Type ZipArchive instance ### Request Example ```javascript import fs from 'fs'; import { ZipArchive } from 'archiver'; const output = fs.createWriteStream('archive.zip'); const archive = new ZipArchive({ zlib: { level: 9 } // Maximum compression }); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Archiver Constructor Source: https://github.com/archiverjs/node-archiver/blob/master/website/docs/archiver_api.md Initializes a new Archiver instance. You can specify the archive format and various options to customize the archiving process, including compression settings and file handling. ```APIDOC ## new Archiver(format, options) ### Description Initializes a new Archiver instance with the specified format and options. ### Parameters - `format` (String) - The archive format to use. - `options` (Object) - Configuration options for the archiver. #### Options ##### Core Options - `statConcurrency` (Number) - Sets the number of workers used to process the internal fs stat queue. Defaults to 4. ##### ZIP Options - `comment` (String) - Sets the zip archive comment. - `forceLocalTime` (Boolean) - Forces the archive to contain local file times instead of UTC. - `forceZip64` (Boolean) - Forces the archive to contain ZIP64 headers. - `namePrependSlash` (Boolean) - Prepends a forward slash to archive file paths. - `store` (Boolean) - Sets the compression method to STORE. - `zlib` (Object) - Passed to zlib to control compression. ##### TAR Options - `gzip` (Boolean) - Compress the tar archive using gzip. - `gzipOptions` (Object) - Passed to zlib to control compression. See tar-stream documentation for additional properties. ``` -------------------------------- ### Chaining Archive Operations Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/INDEX.md Demonstrates how to chain multiple file, directory, and glob operations using method chaining. Most methods return 'this' to enable this pattern. ```javascript archive .file('file1.txt', { name: 'f1.txt' }) .file('file2.txt', { name: 'f2.txt' }) .directory('./src', 'src') .glob('*.md'); ``` -------------------------------- ### Configure Entries Per Glob Pattern Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Pass configuration options to the glob() method for consistent settings across files matching a pattern. This simplifies configuration for sets of files. ```javascript archive.glob('**/*.js', { cwd: './src' }, { prefix: 'src', mode: 0o755 } ); ``` -------------------------------- ### JsonArchive Constructor Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Initializes a new instance of JsonArchive. It accepts an optional options object for stream configuration. ```APIDOC ## JsonArchive Constructor ### Description Initializes a new instance of JsonArchive. It accepts an optional options object for stream configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (JsonOptions) - Optional - Stream configuration options. Defaults to {}. ### JsonOptions Extends TransformOptions from Node.js Stream API. - **highWaterMark** (number) - Optional - Maximum bytes in internal buffer. Defaults to 1048576. - **statConcurrency** (number) - Optional - Concurrent file stat operations. Defaults to 4. ### Return Type JsonArchive instance ### Example: Basic JSON Archive Creation ```javascript import fs from 'fs'; import { JsonArchive } from 'archiver'; const output = fs.createWriteStream('archive.json'); const archive = new JsonArchive(); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); // Result is a JSON array of file objects ``` ``` -------------------------------- ### Archiver Class Constructor Source: https://github.com/archiverjs/node-archiver/blob/master/website/docs/archiver_api.md Instantiates a new Archiver object. Specify the archive format and options during initialization. Options can include core settings, ZIP-specific configurations, or TAR-specific settings like gzip compression. ```javascript new Archiver(format, options); ``` -------------------------------- ### Archive with Progress and Event Tracking Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/README.md Listen for 'progress', 'entry', 'warning', and 'error' events to monitor the archiving process and handle potential issues. ```javascript archive.on('progress', (progress) => { const percent = (progress.fs.processedBytes / progress.fs.totalBytes) * 100; console.log(`Progress: ${percent.toFixed(1)}%`); }); archive.on('entry', (entry) => { console.log(`Appended: ${entry.name}`); }); archive.on('warning', (err) => { if (err.code === 'ENOENT') { console.warn('File not found:', err.path); } else { throw err; } }); archive.on('error', (err) => { throw err; }); ``` -------------------------------- ### Handle ENTRYNOTSUPPORTED Warning Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Listen for the 'warning' event to catch ENTRYNOTSUPPORTED errors, which indicate an unsupported entry type or a special filesystem file type being encountered. The error data contains details about the unsupported entry. ```javascript archive.on('warning', (err) => { if (err.code === 'ENTRYNOTSUPPORTED') { console.warn('Unsupported entry type:', err.data); } }); ``` -------------------------------- ### Basic TAR Creation Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/tar-archive.md Use this snippet to create a basic uncompressed TAR archive. It pipes the archive stream to a file write stream. ```javascript import fs from 'fs'; import { TarArchive } from 'archiver'; const output = fs.createWriteStream('archive.tar'); const archive = new TarArchive(); archive.pipe(output); archive.append('hello', { name: 'hello.txt' }); await archive.finalize(); ``` -------------------------------- ### Create Simple JSON Archive Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Appends individual files (text, buffer, and from path) to a JSON archive. The output is a readable JSON array. ```javascript import fs from 'fs'; import { JsonArchive } from 'archiver'; const output = fs.createWriteStream('archive.json'); const archive = new JsonArchive(); archive.pipe(output); archive.append('Hello World', { name: 'hello.txt' }); archive.append(Buffer.from('binary'), { name: 'data.bin' }); archive.file('/path/to/file.txt', { name: 'file.txt' }); await archive.finalize(); // Output is readable JSON array ``` -------------------------------- ### Create JSON Archive from Directory Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/api-reference/json-archive.md Archives an entire directory and files matching a glob pattern into a JSON manifest. This is useful for creating a manifest of project files. ```javascript const archive = new JsonArchive(); const output = fs.createWriteStream('manifest.json'); archive.pipe(output); archive.directory('./src', 'src'); archive.glob('*.md', { cwd: '.' }); await archive.finalize(); ``` -------------------------------- ### Configure for Many Small Files Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Increase statConcurrency for faster processing of numerous small files. Use a smaller highWaterMark and higher zlib level for better compression. ```javascript const archive = new ZipArchive({ statConcurrency: 8, // More parallel stat calls highWaterMark: 2 * 1024 * 1024, // 2 MB zlib: { level: 9, // Better compression ratio memLevel: 9 } }); ``` -------------------------------- ### ZipOptions Configuration Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/types.md Configure ZIP archive creation with options for comments, time formats, compression, and zlib settings. ```javascript { comment?: string, forceLocalTime?: boolean, forceZip64?: boolean, namePrependSlash?: boolean, store?: boolean, zlib?: object } ``` ```javascript new ZipArchive({ comment: 'Created by my app', zlib: { level: 9 }, store: false }) ``` -------------------------------- ### Entry-Level ZipArchive Compression Override Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/configuration.md Override the default compression method for individual entries in a Zip archive. Use 'store: true' to skip compression for already compressed files. ```javascript // Mix compression levels in single ZIP archive.append(textData, { name: 'document.txt' // Uses default compression (level 6) }); archive.append(jpegData, { name: 'photo.jpg', store: true // No compression (already compressed) }); archive.append(csvData, { name: 'data.csv', store: false // Force compression (very compressible) }); ``` -------------------------------- ### Handle ENOENT (File Not Found) Warning Source: https://github.com/archiverjs/node-archiver/blob/master/_autodocs/errors.md Listen for 'warning' events and specifically check for the 'ENOENT' error code to handle cases where a file does not exist. Archiving continues after this warning. ```javascript archive.on('warning', (err) => { if (err.code === 'ENOENT') { console.warn('File not found:', err.path); // Entry is skipped, archiving continues } else { throw err; // Other warnings should be fatal } }); ```