### Option Table Example Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/MANIFEST.md Demonstrates the format for documenting configuration options, specifying type, default value, context, and description. ```markdown | Option | Type | Default | Context | Description | |---|---|---|---|---| ``` -------------------------------- ### Parameter Table Example Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/MANIFEST.md Shows the structure for documenting function parameters, including their type, requirement, default value, and description. ```markdown | Parameter | Type | Required | Default | Description | |---|---|---|---|---| ``` -------------------------------- ### Custom Backend Implementation Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Example of how to implement a custom backend for Yauzl using `RandomAccessReader`. ```APIDOC ## Implement Custom Backend To use a custom backend, extend `yauzl.RandomAccessReader` and implement the `_readStreamForRange` method. ```javascript class MyReader extends yauzl.RandomAccessReader { _readStreamForRange(start, end) { // Return readable stream for bytes [start, end) } } const zipfile = await yauzl.fromRandomAccessReaderPromise( new MyReader(), totalSize ); ``` ``` -------------------------------- ### Signature Format Example Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/MANIFEST.md Illustrates the standard signature format used for functions within the documentation. ```javascript function name(param1, param2, [optional]) -> ReturnType ``` -------------------------------- ### Creating a Spec-Conformant Zip File with Ambiguous Data Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md This example demonstrates how to create a zip file that challenges streaming parsers by using General Purpose Bit 3 and crafted file content. It highlights potential issues for parsers that do not strictly adhere to the zip specification. ```bash $ echo -ne '\x50\x4b\x07\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > file.txt $ zip -q0 - file.txt | cat > out.zip ``` -------------------------------- ### Read Partial Compressed Data with Start and End Options Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/configuration.md Specify byte offsets to read only a portion of the compressed data. Requires `decodeFileData: false` and `start < end`. The `start` option defines the beginning byte offset, and `end` defines the exclusive end byte offset. ```javascript // Read first 1000 compressed bytes zipfile.openReadStream(entry, { decodeFileData: false, start: 0, end: 1000 }, (err, readStream) => { // Stream provides 1000 bytes of compressed data }); // Skip first 100 bytes, read next 1000 zipfile.openReadStream(entry, { decodeFileData: false, start: 100, end: 1100 }, (err, readStream) => { // Stream provides bytes [100, 1100) }); ``` -------------------------------- ### Iterate Over ZIP Entries with eachEntry() Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-zipfile.md Uses the eachEntry() method to asynchronously iterate over all entries in a ZIP file, providing a more modern alternative to event-based entry handling. This example skips directories and prepares to read file data. ```javascript const yauzl = require("yauzl"); (async () => { const zipfile = await yauzl.openPromise("archive.zip"); try { for await (let entry of zipfile.eachEntry()) { if (entry.fileName.endsWith("/")) { continue; // Skip directories } const readStream = await zipfile.openReadStreamPromise(entry); // Process file data... } } catch (err) { console.error("Error reading entries:", err); } })(); ``` -------------------------------- ### Read File Data Start Position Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md Shows the primary use case of `readLocalFileHeader()`: obtaining the `fileDataStart` property. This is useful for advanced scenarios like reading partial file data. ```javascript const yauzl = require("yauzl"); yauzl.open("archive.zip", {lazyEntries: true}, (err, zipfile) => { if (err) throw err; zipfile.on("entry", (entry) => { zipfile.readLocalFileHeader(entry, {minimal: true}, (err, obj) => { if (err) throw err; console.log(`File data starts at byte ${obj.fileDataStart}`); }); }); }); ``` -------------------------------- ### Read Local File Header (Minimal) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-zipfile.md Reads only the `fileDataStart` property from the Local File Header for an entry. Useful for debugging or advanced scenarios where only the starting byte offset is needed. ```javascript zipfile.readLocalFileHeader(entry, {minimal: true}, (err, obj) => { if (err) throw err; console.log("File data starts at byte:", obj.fileDataStart); }); ``` -------------------------------- ### HTTP Network Reader Example Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-randomaccessreader.md Implements a RandomAccessReader to read zip files over HTTP using Range requests. Requires the 'https' and 'url' modules. Instantiate with the URL of the zip file. ```javascript const util = require("util"); const yauzl = require("yauzl"); const https = require("https"); const { URL } = require("url"); function HttpRangeReader(url) { yauzl.RandomAccessReader.call(this); this.url = url; } util.inherits(HttpRangeReader, yauzl.RandomAccessReader); HttpRangeReader.prototype._readStreamForRange = function(start, end) { const parsedUrl = new URL(this.url); const options = { hostname: parsedUrl.hostname, port: parsedUrl.port, path: parsedUrl.pathname, headers: { "Range": `bytes=${start}-${end - 1}` } }; return new Promise((resolve, reject) => { https.get(options, (res) => { if (res.statusCode !== 206) { reject(new Error(`HTTP ${res.statusCode}`)); } else { resolve(res); } }).on("error", reject); }); }; HttpRangeReader.prototype.close = function(callback) { // No resources to clean up setImmediate(callback); }; // Usage: const reader = new HttpRangeReader("https://example.com/archive.zip"); yauzl.fromRandomAccessReader(reader, 5000000, {lazyEntries: true}, (err, zipfile) => { if (err) throw err; // Use zipfile... }); ``` -------------------------------- ### Implementing _readStreamForRange for LocalFileReader Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-randomaccessreader.md Example of implementing the _readStreamForRange method for a LocalFileReader subclass. This method creates a Node.js readable stream for a specified byte range using fs.createReadStream. ```javascript const util = require("util"); const yauzl = require("yauzl"); const fs = require("fs"); function LocalFileReader(fd) { yauzl.RandomAccessReader.call(this); this.fd = fd; } util.inherits(LocalFileReader, yauzl.RandomAccessReader); LocalFileReader.prototype._readStreamForRange = function(start, end) { return fs.createReadStream(null, { fd: this.fd, start: start, end: end - 1, // fs.createReadStream's end is inclusive autoClose: false }); }; ``` -------------------------------- ### Minimal LocalFileHeader Option Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md Shows the structure of the object received when calling `readLocalFileHeader()` with the `{minimal: true}` option. This is more efficient if only the file data start position is needed. ```javascript { fileDataStart: number // Byte offset where file data begins } ``` -------------------------------- ### HTTP Range Reader Implementation Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/architecture.md Provides an example of implementing a custom `RandomAccessReader` for network ZIP files using HTTP Range requests. This allows reading ZIP archives stored remotely over HTTP. ```javascript class HttpReader extends yauzl.RandomAccessReader { _readStreamForRange(start, end) { // Return stream for [start, end) from HTTP server } } ``` -------------------------------- ### Instantiate LocalFileHeader Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md Demonstrates how to create an instance of the LocalFileHeader class. Typically, instances are obtained from `zipfile.readLocalFileHeader()` rather than direct instantiation. ```javascript const header = new yauzl.LocalFileHeader(); ``` -------------------------------- ### Instantiate an Entry Object Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-entry.md Demonstrates how to manually create a new Entry object. Typically, entries are obtained from ZipFile events or iterations. ```javascript const entry = new yauzl.Entry(); ``` -------------------------------- ### Implement Custom Storage Backend for ZIP Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/examples.md Demonstrates creating a custom `RandomAccessReader` to process ZIP archives from non-file sources like Buffers, networks, or databases. ```javascript const yauzl = require("yauzl"); const util = require("util"); const { Readable } = require("stream"); // Example: read from a Buffer with offset (could be network, database, etc.) class BufferRangeReader extends yauzl.RandomAccessReader { constructor(buffer) { super(); this.buffer = buffer; } _readStreamForRange(start, end) { const slice = this.buffer.slice(start, end); const readable = new Readable(); readable.push(slice); readable.push(null); // EOF return readable; } } (async () => { const buffer = Buffer.from(/* ... binary ZIP data ... */); const reader = new BufferRangeReader(buffer); const zipfile = await yauzl.fromRandomAccessReaderPromise(reader, buffer.length); for await (let entry of zipfile.eachEntry()) { console.log(entry.fileName); } })(); ``` -------------------------------- ### Implementing close() for LocalFileReader Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-randomaccessreader.md Example of implementing the close method for LocalFileReader to close the underlying file descriptor. This is called when the reader is no longer needed. ```javascript LocalFileReader.prototype.close = function(callback) { fs.close(this.fd, callback); }; ``` -------------------------------- ### open(path, [options], [callback]) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Opens a ZIP file from a file path and returns a ZipFile instance through a callback. It supports various configuration options for reading the ZIP file. ```APIDOC ## open(path, [options], [callback]) ### Description Opens a ZIP file from a file path and returns a `ZipFile` instance through a callback. ### Parameters - **path** (string) - yes - File system path to the .zip file - **options** (object) - no - Configuration options for reading the ZIP file. Defaults to `{autoClose: true, lazyEntries: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false}`. - **callback** (function) - no - Callback function receiving `(err, zipfile)`. Throws on error. ### Options - **autoClose** (boolean, default: `true`): Automatically closes the file descriptor when the `end` event is emitted. - **lazyEntries** (boolean, default: `false`): When `false`, entries are emitted as fast as possible. When `true`, entries are emitted only in response to `readEntry()` calls. - **decodeStrings** (boolean, default: `true`): Decodes file names and comments from CP437 or UTF-8 as per the ZIP spec. When `false`, these are returned as `Buffer` objects. - **validateEntrySizes** (boolean, default: `true`): Validates that uncompressed sizes match actual data, providing early detection of zip bomb attacks for stored files. - **strictFileNames** (boolean, default: `false`): When `false`, backslash characters in file names are replaced with forward slashes. When `true`, files with backslashes result in an error. ### Returns Invokes callback with `(err, zipfile)` where `zipfile` is a `ZipFile` instance, or `err` if the End of Central Directory Record is not found or is malformed. ### Example ```javascript const yauzl = require("yauzl"); yauzl.open("archive.zip", {lazyEntries: true}, (err, zipfile) => { if (err) throw err; zipfile.on("entry", (entry) => { console.log(entry.fileName); zipfile.readEntry(); }); zipfile.on("end", () => { console.log("Done reading entries"); }); zipfile.readEntry(); }); ``` ``` -------------------------------- ### Get Modification Date Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-entry.md Retrieves the modification time of the entry as a JavaScript Date object. It intelligently selects the best available timestamp format. ```javascript const date = entry.getLastModDate(); console.log("Modified:", date.toISOString()); ``` ```javascript // Force DOS format (pre-3.2.0 behavior): const dosDate = entry.getLastModDate({forceDosFormat: true}); ``` ```javascript // Interpret DOS as UTC: const utcDate = entry.getLastModDate({timezone: "UTC"}); ``` -------------------------------- ### fromBuffer(buffer, [options], [callback]) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Opens a ZIP file from a Node.js Buffer containing the entire file contents. It accepts the buffer and optional configurations, returning a ZipFile instance via a callback. ```APIDOC ## fromBuffer(buffer, [options], [callback]) ### Description Opens a ZIP file from a `Buffer` containing the entire file contents. ### Parameters - **buffer** (Buffer) - yes - Node.js Buffer containing the complete ZIP file data - **options** (object) - no - Configuration options. Defaults to `{lazyEntries: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false}`. - **callback** (function) - no - Callback function receiving `(err, zipfile)`. Throws on error. ### Returns Invokes callback with `(err, zipfile)`. ### Notes - `autoClose` is always set to `false` and cannot be overridden. - The `ZipFile` never emits a `close` event. - Calling `close()` is not necessary but safe. ### Example ```javascript const yauzl = require("yauzl"); const fs = require("fs"); const buffer = fs.readFileSync("archive.zip"); yauzl.fromBuffer(buffer, {lazyEntries: true}, (err, zipfile) => { if (err) throw err; // Use zipfile... }); ``` ``` -------------------------------- ### Get and Format Last Modification Date Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Retrieves the last modification date of a ZIP entry and logs it in ISO format. It also shows how to force the date into DOS format. ```javascript const date = entry.getLastModDate(); console.log("Modified:", date.toISOString()); // Force DOS format (pre-3.2.0): const dosDate = entry.getLastModDate({forceDosFormat: true}); ``` -------------------------------- ### Open Options Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/types.md Configuration options for opening a ZIP archive with `yauzl.open()` or `yauzl.fromFd()`. ```typescript interface OpenOptions { autoClose?: boolean; // Default: true for open(), false for fromFd() lazyEntries?: boolean; // Default: false decodeStrings?: boolean; // Default: true validateEntrySizes?: boolean; // Default: true strictFileNames?: boolean; // Default: false } ``` -------------------------------- ### Yauzl Open Function Options Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/configuration.md Demonstrates the various options that can be passed to the open, fromFd, fromBuffer, or fromRandomAccessReader functions in Yauzl. ```javascript yauzl.open("archive.zip", { autoClose: true, lazyEntries: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false }, callback); ``` -------------------------------- ### openReadStreamLowLevel Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Opens a read stream at a specific position within the zip file. This is a low-level function for advanced use cases and requires manual handling of file data start and size. ```APIDOC ## openReadStreamLowLevel(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) ### Description Opens a low-level read stream for a portion of a zip file. This function is intended for advanced use cases and bypasses much of the standard validation performed by `openReadStream()`. ### Parameters * `fileDataStart` (integer) - The starting position of the file data in the zip archive. * `compressedSize` (integer) - The compressed size of the file data. * `relativeStart` (integer) - The starting offset within the file data. Must be a non-negative integer. * `relativeEnd` (integer) - The ending offset within the file data. Must be a non-negative integer. * `decompress` (boolean) - Indicates whether the data should be decompressed using zlib inflate. * `uncompressedSize` (integer) - The uncompressed size of the file data. Used when `validateEntrySizes` is true. * `callback` - A function that receives `(err, readStream)`. ``` -------------------------------- ### fromFd(fd, [options], [callback]) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Opens a ZIP file from an already-open file descriptor. It takes a file descriptor and optional configuration, returning a ZipFile instance via a callback. ```APIDOC ## fromFd(fd, [options], [callback]) ### Description Opens a ZIP file from an already-open file descriptor. ### Parameters - **fd** (number) - yes - Open file descriptor from `fs.open()` - **options** (object) - no - Configuration options. Defaults to `{autoClose: false, lazyEntries: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false}`. - **callback** (function) - no - Callback function receiving `(err, zipfile)`. Throws on error. ### Returns Invokes callback with `(err, zipfile)` where `zipfile` is a `ZipFile` instance. ### Notes - The fd must support random access (not a socket or pipe). - Default `autoClose` is `false` for this function (you own the fd lifecycle). ### Example ```javascript const yauzl = require("yauzl"); const fs = require("fs"); fs.open("archive.zip", "r", (err, fd) => { if (err) throw err; yauzl.fromFd(fd, {lazyEntries: true}, (err, zipfile) => { if (err) throw err; // Use zipfile... zipfile.close(); }); }); ``` ``` -------------------------------- ### Unzip a file using async/await Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md This snippet demonstrates how to open a zip file and iterate through its entries using modern JavaScript async/await syntax. It handles both directory and file entries, streaming file content to a destination. ```javascript const yauzl = require("yauzl"); (async () => { try { const zipfile = await yauzl.openPromise("path/to/file.zip"); for await (let entry of zipfile.eachEntry()) { if (entry.fileName.endsWith("/")) { // Directory file names end with '/'. // Note that entries for directories themselves are optional. // An entry's fileName implicitly requires its parent directories to exist. continue; } else { // file entry const readStream = await zipfile.openReadStreamPromise(entry); await stream.promises.pipeline(readStream, somewhere); } } } catch (err) { // Indicates a malformed zipfile or I/O error. throw err; } })(); ``` -------------------------------- ### List ZIP Contents Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Asynchronously opens a ZIP archive and iterates through its entries, logging the file name and uncompressed size of each entry. This is a common starting point for inspecting ZIP file contents. ```javascript const yauzl = require("yauzl"); (async () => { const zipfile = await yauzl.openPromise("archive.zip"); for await (let entry of zipfile.eachEntry()) { console.log(entry.fileName, entry.uncompressedSize); } })(); ``` -------------------------------- ### Entry Constructor Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-entry.md The Entry constructor can be used for manual instantiation, though typically entries are obtained through ZipFile events or iteration. ```APIDOC ## Constructor The `Entry` constructor is available for manual instantiation but typically entries are obtained from `ZipFile` events or `eachEntry()` iteration. ```javascript const entry = new yauzl.Entry(); ``` ``` -------------------------------- ### Implement Custom Backend for ZIP Files Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Demonstrates how to create a custom RandomAccessReader to read ZIP files from a non-standard source, such as a network stream or a custom file system. ```javascript class MyReader extends yauzl.RandomAccessReader { _readStreamForRange(start, end) { // Return readable stream for bytes [start, end) } } const zipfile = await yauzl.fromRandomAccessReaderPromise( new MyReader(), totalSize ); ``` -------------------------------- ### Read Local File Header with Minimal Option Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/configuration.md Control the amount of information returned by `readLocalFileHeader`. Set `minimal` to `true` to only retrieve the `fileDataStart` offset, or `false` to get the full `LocalFileHeader` object. ```javascript zipfile.readLocalFileHeader(entry, { minimal: false }, callback); ``` -------------------------------- ### Low-Level Stream Opening with Saved Parameters Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md Demonstrates how to combine `readLocalFileHeader()` with `openReadStreamLowLevel()` to obtain serializable read parameters. These parameters can be saved and used later to reopen a file stream, even in a different process. ```javascript zipfile.readLocalFileHeader(entry, {minimal: true}, (err, minimal) => { if (err) throw err; // Save these parameters for later use (even in a different process) const params = { fileDataStart: minimal.fileDataStart, compressedSize: entry.compressedSize, relativeStart: 0, relativeEnd: entry.compressedSize, decompress: entry.compressionMethod === 8, uncompressedSize: entry.uncompressedSize }; // Later, reopen the file and use the saved parameters zipfile.openReadStreamLowLevel( params.fileDataStart, params.compressedSize, params.relativeStart, params.relativeEnd, params.decompress, params.uncompressedSize, (err, readStream) => { if (err) throw err; // Use readStream... } ); }); ``` -------------------------------- ### Promise wrapper for readLocalFileHeader Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Demonstrates how to use the promise-based wrapper for `readLocalFileHeader`. The promise resolves with the local file header data or rejects on error. ```javascript readLocalFileHeaderPromise(entry, [options]) ``` -------------------------------- ### eachEntry() Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-zipfile.md Returns an async iterable/iterator that yields each entry in the ZIP file. This provides `for await...of` support as an alternative to using `readEntry()` and event handlers. ```APIDOC ## eachEntry() ### Description Returns an async iterable/iterator that yields each entry. Provides `for await...of` support as an alternative to `readEntry()` and event handlers. ### Returns An object implementing both the async iterable and async iterator protocols: - `[Symbol.asyncIterator]()`: Returns itself - `next()`: Returns `Promise<{value: Entry} | {done: true}>` - `return(value)`: Cleanup and return `{done: true}` - `throw(value)`: Cleanup and throw ### Constraints - Can only be called once per `ZipFile` instance - `lazyEntries` must be `true` - Cannot be mixed with `readEntry()` on the same instance - `Event: "entry"` and `Event: "end"` are not recommended with `eachEntry()` ### Example ```javascript const yauzl = require("yauzl"); (async () => { const zipfile = await yauzl.openPromise("archive.zip"); try { for await (let entry of zipfile.eachEntry()) { if (entry.fileName.endsWith("/")) { continue; // Skip directories } const readStream = await zipfile.openReadStreamPromise(entry); // Process file data... } } catch (err) { console.error("Error reading entries:", err); } })(); ``` ``` -------------------------------- ### Get File Modification Dates from ZIP Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/examples.md Retrieves the last modification date for files within a ZIP archive. Supports automatic handling of extra fields and options for forcing DOS format or interpreting dates as UTC. ```javascript const yauzl = require("yauzl"); (async () => { const zipfile = await yauzl.openPromise("archive.zip"); for await (let entry of zipfile.eachEntry()) { // Get modification date with automatic extra field handling const date = entry.getLastModDate(); console.log(`${entry.fileName}: ${date.toISOString()}`); // Force DOS format (pre-3.2.0 behavior) const dosDate = entry.getLastModDate({forceDosFormat: true}); // Interpret DOS format as UTC const utcDate = entry.getLastModDate({timezone: "UTC"}); } })(); ``` -------------------------------- ### Read Raw Compressed ZIP Entry Data Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Opens a read stream for a ZIP entry without decompressing the data. This is useful when you need to access the raw compressed bytes of a file within the archive, for example, for custom processing or analysis. ```javascript const stream = await zipfile.openReadStreamPromise(entry, {decodeFileData: false}); // stream provides compressed bytes as-is ``` -------------------------------- ### Get Entry Last Modification Date with Timezone and Format Options Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/configuration.md Parse the last modification date of an entry, specifying the timezone interpretation or forcing DOS format. The `timezone` option can be set to 'local' or 'UTC', while `forceDosFormat` ignores extended timestamp fields. ```javascript const date = entry.getLastModDate({ timezone: "local", forceDosFormat: false }); ``` -------------------------------- ### yauzl.fromFdPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Promise-based wrapper around `fromFd()`. Always sets `lazyEntries: true`. ```APIDOC ## fromFdPromise(fd, [options]) ### Description Promise-based wrapper around `fromFd()`. Always sets `lazyEntries: true`. ### Method `function fromFdPromise(fd, options) -> Promise` ### Parameters #### Path Parameters - **fd** (number) - Required - Open file descriptor #### Query Parameters - **options** (object) - Optional - Configuration options (lazyEntries is forced to true) ### Returns `Promise` that resolves to a `ZipFile` instance or rejects with an error. ``` -------------------------------- ### fromFdPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Provides a Promise-based wrapper for `fromFd()`. It resolves with the zipfile object upon successful opening or rejects if an error occurs. `options.lazyEntries` is enforced to be `true`. ```APIDOC ## fromFdPromise(fd, [options]) ### Description Wraps `fromFd()` with `Promise` semantics. The returned promise is rejected if the `callback` for `fromFd()` receives an `err`, otherwise the promise is resolved with the `zipfile`. `options` may be omitted or `null`, and `fd` and `options` are passed to `fromFd()`. `options.lazyEntries` is always set to `true`, overriding any value you pass in. This is required for using `zipfile.eachEntry()`, which you probably also want to use. ### Method Promise-based function ### Parameters #### Path Parameters - **fd** (number) - Required - The file descriptor of the zip file. - **options** (object) - Optional - Options to pass to the underlying `fromFd()` function. `lazyEntries` will be forced to `true`. ### Response #### Success Response - **zipfile** - The opened zip file object. ``` -------------------------------- ### yauzl.LocalFileHeader Constructor Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md The constructor for the LocalFileHeader class is available but performs no initialization. Instances are typically obtained from `zipfile.readLocalFileHeader()`. ```APIDOC ## new yauzl.LocalFileHeader() ### Description Creates a new instance of the LocalFileHeader class. Note that this constructor performs no initialization and is typically not used directly; instances are usually obtained from `zipfile.readLocalFileHeader()`. ### Method `new` ### Parameters None ``` -------------------------------- ### Serialize and Deserialize Zip File Data Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-zipfile.md Demonstrates how to serialize parameters for zip file data and later use them to open a low-level read stream. Ensure proper bounds checking or use with `decodeFileData: false`. ```javascript const params = { fileDataStart: localHeader.fileDataStart, compressedSize: entry.compressedSize, relativeStart: 0, relativeEnd: entry.compressedSize, decompress: entry.compressionMethod === 8, uncompressedSize: entry.uncompressedSize }; zipfile.openReadStreamLowLevel( params.fileDataStart, params.compressedSize, params.relativeStart, params.relativeEnd, params.decompress, params.uncompressedSize, (err, readStream) => { if (err) throw err; readStream.pipe(process.stdout); } ); ``` -------------------------------- ### yauzl.fromRandomAccessReader Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Opens a ZIP file from a RandomAccessReader. This is a callback-based function. ```APIDOC ## yauzl.fromRandomAccessReader(reader, totalSize, [options], callback) ### Description Opens a ZIP file from a `RandomAccessReader`. This function is callback-based. ### Parameters #### Path Parameters - **reader** (RandomAccessReader) - Required - Subclass of `RandomAccessReader` implementing `_readStreamForRange()` - **totalSize** (number) - Required - Total byte size of the ZIP file #### Query Parameters - **options** (object) - Optional - Configuration options (`autoClose: true`, `lazyEntries: false`, `decodeStrings: true`, `validateEntrySizes: true`, `strictFileNames: false`) - **callback** (function) - Optional - Callback function receiving `(err, zipfile)` ### Returns Invokes callback with `(err, zipfile)`. ### Request Example ```javascript const yauzl = require("yauzl"); const util = require("util"); class NetworkReader extends yauzl.RandomAccessReader { constructor(url) { super(); this.url = url; } _readStreamForRange(start, end) { // Return a readable stream of bytes [start, end) // Implement based on your storage backend } } const reader = new NetworkReader("https://example.com/archive.zip"); yauzl.fromRandomAccessReader(reader, 1000000, {lazyEntries: true}, (err, zipfile) => { if (err) throw err; // Use zipfile... }); ``` ``` -------------------------------- ### Compare Central and Local Headers Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-localfileheader.md Illustrates how to compare the data from a Central Directory Record (`entry`) with a Local File Header (`localHeader`). This is useful for debugging or auditing the structure of ZIP files. ```javascript zipfile.readLocalFileHeader(entry, (err, localHeader) => { if (err) throw err; console.log("Central Directory:", { fileName: entry.fileName, uncompressedSize: entry.uncompressedSize, compressedSize: entry.compressedSize }); console.log("Local File Header:", { fileName: localHeader.fileName.toString(), uncompressedSize: localHeader.uncompressedSize, compressedSize: localHeader.compressedSize }); // In well-formed ZIP files, these should match }); ``` -------------------------------- ### Open Zip File by Path Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Opens a zip file from a given path. Options can control auto-closing, lazy entry loading, string decoding, entry size validation, and strict filename handling. The callback receives an error or a ZipFile instance. ```javascript zipfile.once("end", function() { zipfile.close(); }); ``` -------------------------------- ### Extract Files with Progress Tracking Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/examples.md Extracts all files from a ZIP archive, creating directories as needed and displaying extraction progress. Requires 'yauzl', 'fs', and 'path'. ```javascript const yauzl = require("yauzl"); const fs = require("fs"); const path = require("path"); (async () => { const zipfile = await yauzl.openPromise("archive.zip"); for await (let entry of zipfile.eachEntry()) { if (entry.fileName.endsWith("/")) { // Create directory const dir = path.dirname(entry.fileName); if (dir) { fs.mkdirSync(dir, {recursive: true}); } continue; } // Ensure directory exists const dir = path.dirname(entry.fileName); if (dir) { fs.mkdirSync(dir, {recursive: true}); } // Extract file const readStream = await zipfile.openReadStreamPromise(entry); const writeStream = fs.createWriteStream(entry.fileName); let bytesRead = 0; readStream.on("data", (chunk) => { bytesRead += chunk.length; const percent = ((bytesRead / entry.uncompressedSize) * 100).toFixed(1); process.stdout.write(`\r${entry.fileName}: ${percent}%`); }); await new Promise((resolve, reject) => { readStream.pipe(writeStream); writeStream.on("finish", resolve); writeStream.on("error", reject); readStream.on("error", reject); }); console.log(); // newline } })(); ``` -------------------------------- ### fromRandomAccessReaderPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Provides a Promise-based wrapper for `fromRandomAccessReader()`. It resolves with the zipfile object or rejects if an error occurs. `options.lazyEntries` is enforced to be `true`. ```APIDOC ## fromRandomAccessReaderPromise(reader, totalSize, [options]) ### Description Wraps `fromRandomAccessReader()` with `Promise` semantics. The returned promise is rejected if the `callback` for `fromRandomAccessReader()` receives an `err`, otherwise the promise is resolved with the `zipfile`. `options` may be omitted or `null`, and `reader`, `totalSize`, and `options` are passed to `fromRandomAccessReader()`. `options.lazyEntries` is always set to `true`, overriding any value you pass in. This is required for using `zipfile.eachEntry()`, which you probably also want to use. ### Method Promise-based function ### Parameters #### Path Parameters - **reader** (RandomAccessReader) - Required - The reader object. - **totalSize** (number) - Required - The total size of the zip file. - **options** (object) - Optional - Options to pass to the underlying `fromRandomAccessReader()` function. `lazyEntries` will be forced to `true`. ### Response #### Success Response - **zipfile** - The opened zip file object. ``` -------------------------------- ### fromRandomAccessReader(reader, totalSize, [options], [callback]) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Opens a ZIP file using a custom `RandomAccessReader` implementation, allowing for custom storage backends. This function is designed for advanced use cases where ZIP data is not stored in a standard file system. ```APIDOC ## fromRandomAccessReader(reader, totalSize, [options], [callback]) ### Description Opens a ZIP file using a custom `RandomAccessReader` implementation, allowing custom storage backends. ### Parameters - **reader** (RandomAccessReader) - yes - An object implementing the `RandomAccessReader` interface. - **totalSize** (number) - yes - The total size of the ZIP file in bytes. - **options** (object) - no - Configuration options. - **callback** (function) - no - Callback function receiving `(err, zipfile)`. ``` -------------------------------- ### openPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Wraps the `open()` function with Promise semantics for asynchronous zip file handling. It resolves with the zipfile object or rejects if an error occurs during opening. `options.lazyEntries` is always set to `true`. ```APIDOC ## openPromise(path, [options]) ### Description Wraps `open()` with `Promise` semantics. The returned promise is rejected if the `callback` for `open()` receives an `err`, otherwise the promise is resolved with the `zipfile`. `options` may be omitted or `null`, and `path` and `options` are passed to `open()`. `options.lazyEntries` is always set to `true`, overriding any value you pass in. This is required for using `zipfile.eachEntry()`, which you probably also want to use. ### Method Promise-based function ### Parameters #### Path Parameters - **path** (string) - Required - The path to the zip file. - **options** (object) - Optional - Options to pass to the underlying `open()` function. `lazyEntries` will be forced to `true`. ### Response #### Success Response - **zipfile** - The opened zip file object. ``` -------------------------------- ### fromBuffer(buffer, [options], [callback]) Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Reads from a Buffer in memory. Options are similar to `open()`, but `autoClose` is ignored. The `ZipFile` acquired from this method will never emit a `close` event, and calling `close()` is not necessary. ```APIDOC ## fromBuffer(buffer, [options], [callback]) ### Description Reads from a Buffer in memory. Options are similar to `open()`, but `autoClose` is ignored. The `ZipFile` acquired from this method will never emit a `close` event, and calling `close()` is not necessary. ### Parameters #### Path Parameters - **buffer** (Buffer) - Required - The Buffer containing the zip file data. #### Options - **lazyEntries** (boolean) - Optional - Defaults to `false`. If true, entries are read only when `readEntry()` is called. If false, 'entry' events are emitted as fast as possible. - **decodeStrings** (boolean) - Optional - Defaults to `true`. If true, strings are decoded using CP437 or UTF-8. If false, `zipfile.comment`, `entry.fileName`, and `entry.fileComment` will be Buffers, Info-ZIP Unicode Path Extra Field will be ignored, and automatic file name validation will not be performed. - **validateEntrySizes** (boolean) - Optional - Defaults to `true`. Ensures an entry's reported uncompressed size matches its actual uncompressed size. - **strictFileNames** (boolean) - Optional - Defaults to `false`. If true and `decodeStrings` is true, entries with backslashes in their file names will result in an error. If false, backslashes are replaced with forward slashes. #### Callback - **callback** (function) - Receives `(err, zipfile)` arguments. `err` is provided if the End of Central Directory Record cannot be found or appears malformed. `zipfile` is an instance of `ZipFile` on success. ``` -------------------------------- ### Manually Read ZIP Entry with lazyEntries Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-zipfile.md Demonstrates how to manually trigger reading the next entry in a ZIP file when the lazyEntries option is set to true. This pattern is used to control entry processing flow. ```javascript yauzl.open("archive.zip", {lazyEntries: true}, (err, zipfile) => { if (err) throw err; zipfile.on("entry", (entry) => { console.log(entry.fileName); zipfile.readEntry(); // Request next entry }); zipfile.readEntry(); // Start ``` -------------------------------- ### List Archive Contents (Promise API) Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/examples.md Utilize the promise-based API with async/await for a more modern approach to listing ZIP archive entries. Requires 'yauzl'. ```javascript const yauzl = require("yauzl"); (async () => { try { const zipfile = await yauzl.openPromise("archive.zip"); for await (let entry of zipfile.eachEntry()) { if (entry.fileName.endsWith("/")) { console.log("Directory:", entry.fileName); } else { console.log("File:", entry.fileName, `(${entry.uncompressedSize} bytes)`); } } } catch (err) { console.error("Error:", err); } })(); ``` -------------------------------- ### fromBufferPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Offers a Promise-based interface for `fromBuffer()`. The promise resolves with the zipfile object on success or rejects on error. `options.lazyEntries` is automatically set to `true`. ```APIDOC ## fromBufferPromise(buffer, [options]) ### Description Wraps `fromBuffer()` with `Promise` semantics. The returned promise is rejected if the `callback` for `fromBuffer()` receives an `err`, otherwise the promise is resolved with the `zipfile`. `options` may be omitted or `null`, and `buffer` and `options` are passed to `fromBuffer()`. `options.lazyEntries` is always set to `true`, overriding any value you pass in. This is required for using `zipfile.eachEntry()`, which you probably also want to use. ### Method Promise-based function ### Parameters #### Path Parameters - **buffer** (Buffer) - Required - The buffer containing the zip file data. - **options** (object) - Optional - Options to pass to the underlying `fromBuffer()` function. `lazyEntries` will be forced to `true`. ### Response #### Success Response - **zipfile** - The opened zip file object. ``` -------------------------------- ### Streaming Design Pipeline Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/architecture.md Illustrates the data flow for streaming file data from a ZIP archive, emphasizing that large files are never fully buffered in memory. Each stage in the pipeline handles specific tasks like reading, decompression, and validation. ```text entry.openReadStream() → fs.createReadStream(start, end) [buffers ~64KB] → zlib.createInflateRaw() [internal decompression buffer] → AssertByteCountStream() [validates size] → caller's writable stream [e.g., fs.createWriteStream] ``` -------------------------------- ### Open ZIP from Random Access Reader with Promises Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Wraps the fromRandomAccessReader() function with Promise semantics for asynchronous reader handling. Ensures lazyEntries is true for zipfile.eachEntry(). ```javascript yauzl.fromRandomAccessReaderPromise(reader, totalSize, [options]) ``` -------------------------------- ### Open ZIP from File Descriptor with Promise Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Provides a promise-based wrapper to open a ZIP file using an existing file descriptor. Similar to `openPromise`, `lazyEntries` is forced to true. ```javascript function fromFdPromise(fd, options) -> Promise ``` -------------------------------- ### Promise wrapper for openReadStreamLowLevel Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md Illustrates the promise-based wrapper for `openReadStreamLowLevel`. This function provides promise semantics for low-level stream opening, passing all arguments directly to the underlying function. ```javascript openReadStreamLowLevelPromise(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize) ``` -------------------------------- ### yauzl.openPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Promise-based wrapper around `open()`. Always sets `lazyEntries: true`. ```APIDOC ## openPromise(path, [options]) ### Description Promise-based wrapper around `open()`. Always sets `lazyEntries: true`. ### Method `function openPromise(path, options) -> Promise` ### Parameters #### Path Parameters - **path** (string) - Required - File system path to the .zip file #### Query Parameters - **options** (object) - Optional - Configuration options (lazyEntries is forced to true) ### Returns `Promise` that resolves to a `ZipFile` instance or rejects with an error. ### Request Example ```javascript const yauzl = require("yauzl"); (async () => { try { const zipfile = await yauzl.openPromise("archive.zip"); for await (let entry of zipfile.eachEntry()) { console.log(entry.fileName); } } catch (err) { console.error(err); } })(); ``` ``` -------------------------------- ### Yauzl API: Entry Methods Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/README.md Details the methods available on an Entry object for retrieving metadata like modification date and checking file properties. ```javascript entry.getLastModDate([options]) entry.canDecodeFileData() entry.isEncrypted() entry.isCompressed() // Deprecated ``` -------------------------------- ### Unzip a file using callbacks Source: https://github.com/thejoshwolfe/yauzl/blob/master/README.md This snippet shows how to unzip a file using traditional Node.js callbacks. It opens the zip file with lazy entry loading and processes each entry, streaming file content when encountered. ```javascript var yauzl = require("yauzl"); yauzl.open("path/to/file.zip", {lazyEntries: true}, function(err, zipfile) { if (err) throw err; zipfile.readEntry(); zipfile.on("entry", function(entry) { if (entry.fileName.endsWith("/")) { // Ignore directory entry. zipfile.readEntry(); } else { // file entry zipfile.openReadStream(entry, function(err, readStream) { if (err) throw err; readStream.on("end", function() { zipfile.readEntry(); }); readStream.pipe(somewhere); }); } }); }); ``` -------------------------------- ### yauzl.fromRandomAccessReaderPromise Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Promise-based wrapper around `fromRandomAccessReader()`. Always sets `lazyEntries: true`. ```APIDOC ## fromRandomAccessReaderPromise(reader, totalSize, [options]) ### Description Promise-based wrapper around `fromRandomAccessReader()`. Always sets `lazyEntries: true`. ### Method `function fromRandomAccessReaderPromise(reader, totalSize, options) -> Promise` ### Parameters #### Path Parameters - **reader** (RandomAccessReader) - Required - RandomAccessReader implementation - **totalSize** (number) - Required - Total size in bytes #### Query Parameters - **options** (object) - Optional - Configuration options (lazyEntries is forced to true) ### Returns `Promise` that resolves to a `ZipFile` instance or rejects with an error. ``` -------------------------------- ### Open ZIP from Random Access Reader Source: https://github.com/thejoshwolfe/yauzl/blob/master/_autodocs/api-reference-core.md Demonstrates how to open a ZIP file using a custom RandomAccessReader implementation. This is useful for reading ZIP archives from network streams or other non-standard storage. Ensure your reader implements `_readStreamForRange`. ```javascript const yauzl = require("yauzl"); const util = require("util"); class NetworkReader extends yauzl.RandomAccessReader { constructor(url) { super(); this.url = url; } _readStreamForRange(start, end) { // Return a readable stream of bytes [start, end) // Implement based on your storage backend } } const reader = new NetworkReader("https://example.com/archive.zip"); yauzl.fromRandomAccessReader(reader, 1000000, {lazyEntries: true}, (err, zipfile) => { if (err) throw err; // Use zipfile... }); ```