### Install adm-zip with npm Source: https://github.com/cthackers/adm-zip/wiki/How-to-Install Use this command to install the adm-zip library via npm. Ensure you have Node.js and npm installed. ```bash $ npm install adm-zip ``` -------------------------------- ### Read and Process Zip Entries Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP This example demonstrates how to load a zip file, iterate through its entries, and read the content of each entry as text. Ensure the zip file exists at the specified path. ```javascript // loads and parses existing zip file local_file.zip var zip = new Zip("local_file.zip"); // get all entries and iterate them zip.getEntries().forEach(function(entry) { var entryName = entry.entryName; var decompressedData = zip.readFile(entry); // decompressed buffer of the entry console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry }); ``` -------------------------------- ### Install adm-zip by downloading zip Source: https://github.com/cthackers/adm-zip/wiki/How-to-Install Download the zip or tarball from the GitHub releases page and extract the zip.js file into your project. This is an alternative to package managers. ```bash Download zip or tarball from [download page](https://github.com/cthackers/adm-zip/downloads) and extract the zip.js in your project ``` -------------------------------- ### Basic Usage of ADM-ZIP Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP-Introduction Demonstrates reading zip files, extracting entries, and creating new zip archives. Includes examples for reading entries, extracting specific files, and extracting all contents. Also shows how to add files, add local files, and write to a buffer or disk. ```javascript var AdmZip = require('adm-zip'); // reading archives var zip = new AdmZip("./my_file.zip"); var zipEntries = zip.getEntries(); // an array of ZipEntry records zipEntries.forEach(function(zipEntry) { console.log(zipEntry.toString()); // outputs zip entries information if (zipEntry.entryName == "my_file.txt") { console.log(zipEntry.data.toString('utf8')); } }); // outputs the content of some_folder/my_file.txt console.log(zip.readAsText("some_folder/my_file.txt")); // extracts the specified file to the specified location zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true) // extracts everything zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true); // creating archives var zip = new AdmZip(); // add file directly zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here"); // add local file zip.addLocalFile("/home/me/some_picture.png"); // get everything as a buffer var willSendthis = zip.toBuffer(); // or write everything to disk zip.writeZip(/*target file name*/"/home/me/files.zip"); ``` -------------------------------- ### Shannon-Fano Tree Encoding Example Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md An example illustrating the encoding of a Shannon-Fano tree. Note that actual trees used in Imploding are larger, typically 64 or 256 entries. ```hex 0x02, 0x42, 0x01, 0x13 ``` -------------------------------- ### Import adm-zip Module Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP This is the initial step to use the adm-zip library in your Node.js project. It requires the module to be installed via npm. ```javascript var Zip = require("adm-zip"); ``` -------------------------------- ### String comment Source: https://github.com/cthackers/adm-zip/wiki/ZipFile Allows getting or setting the comment associated with the zip archive. ```APIDOC ## String comment ### Description Getter/Setter for archive comment. ### Method GET/SET (conceptual) ### Endpoint N/A (Property access on ZipFile object) ### Returns - **String** - The current archive comment (getter). ### Parameters - **comment** (String) - Optional - The new comment to set for the archive (setter). ``` -------------------------------- ### constructor Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Initializes a new ADM-ZIP instance. It can either load an existing zip file from a given path or create a new in-memory zip archive if no path is provided. ```APIDOC ## constructor(filePath) ### Description Initializes a new ADM-ZIP instance. It can either load an existing zip file from a given path or create a new in-memory zip archive if no path is provided. ### Parameters #### Path Parameters - **filePath** (String) - Optional - The path to the zip file to load. ### Request Example ```javascript // loads and parses existing zip file local_file.zip var zip = new Zip("local_file.zip"); // creates new in memory zip var zip = new Zip(); ``` ``` -------------------------------- ### Get ZIP Content as Buffer Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Retrieves the entire content of the ZIP archive as a Node.js Buffer object. This method supports asynchronous operations with callbacks for success, failure, and item processing. ```javascript zip.toBuffer(function (buffer) { // Process the buffer }, function (error) { // Handle error }, function (fileName) { // Item start callback }, function (fileName) { // Item end callback }); ``` -------------------------------- ### Initialize adm-zip Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Instantiate the ADM-ZIP class. You can either load an existing zip file by providing its path or create a new in-memory zip archive. ```javascript // loads and parses existing zip file local_file.zip var zip = new Zip("local_file.zip"); // creates new in memory zip var zip = new Zip(); ``` -------------------------------- ### Initialize Traditional PKWARE Encryption Keys Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md Provides the initial constant values for the three 32-bit keys used in traditional PKWARE encryption. These values are used to initialize the encryption keys before processing the encryption header. ```plaintext Key(0) <- 305419896 Key(1) <- 591751049 Key(2) <- 878082192 ``` -------------------------------- ### toBuffer() Source: https://github.com/cthackers/adm-zip/wiki/ZipFile Converts the entire zip archive into a Buffer object. ```APIDOC ## toBuffer( ) ### Description Returns the zip file as a Buffer. ### Method GET (conceptual) ### Endpoint N/A (Method call on ZipFile object) ### Returns - **Buffer** - The zip file content as a Buffer. ``` -------------------------------- ### ADM-ZIP with Electron Original-FS Source: https://github.com/cthackers/adm-zip/blob/master/README.md Shows how to configure ADM-ZIP to use Electron's original file system module by passing it in the constructor's options. This is useful for compatibility with bundlers like rollup. ```javascript const AdmZip = require("adm-zip"); const OriginalFs = require("original-fs"); // reading archives const zip = new AdmZip("./my_file.zip", { fs: OriginalFs }); . ``` -------------------------------- ### Pack PPMd Parameters into 2-byte Field Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md Illustrates how to pack Model order, Sub-allocator size, and Model restoration method into a 2-byte field for PPMd compression. Values are stored in Intel low-byte/high-byte order. ```plaintext wPPMd = (Model order - 1) + ((Sub-allocator size - 1) << 4) + (Model restoration method << 12) ``` -------------------------------- ### addFile Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Programmatically creates a new entry (file or directory) within the zip archive. Directories are created if the entry name ends with '/'. ```APIDOC ## addFile(entryName, content, comment, attr) ### Description Programmatically creates a new entry (file or directory) within the zip archive. Directories are created if the entry name ends with '/'. ### Parameters #### Path Parameters - **entryName** (String) - Required - The name for the new entry. Use a trailing '/' for directories. - **content** (Buffer) - Required - The content of the file. Use null for directories. - **comment** (String) - Optional - A comment for the new entry. - **attr** (Number) - Optional - Attributes for the new entry. ### Returns - **void** ``` -------------------------------- ### Pseudo-code for Encryption Process Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md This pseudo-code outlines the steps involved in encrypting files within a ZIP archive. It details key derivation, random data generation, and the iterative encryption of each file. ```pseudo-code Password = GetUserPassword() MasterSessionKey = DeriveKey(SHA1(Password)) RD = CryptographicStrengthRandomData() For Each File IV = CryptographicStrengthRandomData() VData = CryptographicStrengthRandomData() VCRC32 = CRC32(VData) FileSessionKey = DeriveKey(SHA1(IV + RD)) ErdData = Encrypt(RD,MasterSessionKey,IV) Encrypt(VData + VCRC32 + FileData, FileSessionKey,IV) Done ``` -------------------------------- ### Decrypt Encryption Header with Update Keys Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md Initializes encryption keys using random data from the header to prevent plaintext attacks. Reads 12 bytes, XORs them with decrypted bytes, and updates keys. ```pseudocode loop for i <- 0 to 11 C <- buffer(i) ^ decrypt_byte() update_keys(C) buffer(i) <- C end loop ``` -------------------------------- ### toBuffer Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Returns the zip archive's content as a Buffer object. Supports asynchronous callbacks for success, failure, and item processing. ```APIDOC ## toBuffer ### Description Returns the entire zip file content as a Buffer. This method supports asynchronous operations with callbacks for different stages of the process. ### Method Signature `toBuffer(Function onSuccess, Function onFail, Function onItemStart, Function onItemEnd)` ### Parameters * **onSuccess** (Function) - Callback function executed upon successful completion. Receives the Buffer object as an argument: `onSuccess(Buffer buffer)`. * **onFail** (Function) - Callback function executed if an error occurs. Receives the error message as an argument: `onFail(String error)`. * **onItemStart** (Function) - Callback function executed when processing of an item starts. Receives the item's file name: `onItemStart(String fileName)`. * **onItemEnd** (Function) - Callback function executed when processing of an item ends. Receives the item's file name: `onItemEnd(String fileName)`. ### Examples ```javascript zip.toBuffer( (buffer) => { console.log("Zip content as buffer:", buffer); }, (error) => { console.error("Error getting buffer:", error); }, (fileName) => { console.log("Starting item:", fileName); }, (fileName) => { console.log("Finished item:", fileName); } ); ``` ``` -------------------------------- ### extractAllTo Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Extracts all entries from the archive to a specified target directory on the file system. ```APIDOC ## extractAllTo(targetPath, overwrite) ### Description Extracts all entries from the archive to a specified target directory on the file system. ### Parameters #### Path Parameters - **targetPath** (String) - Required - The directory where all entries will be extracted. - **overwrite** (Boolean) - Optional - If true, existing files will be overwritten. Defaults to false. ### Returns - **void** ``` -------------------------------- ### Shannon-Fano Tree Construction Algorithm Source: https://github.com/cthackers/adm-zip/blob/master/APPNOTE.md Algorithm for constructing Shannon-Fano codes from bit lengths. This process involves sorting bit lengths, generating initial codes, and then reversing bits and restoring the original order. ```pseudocode Code <- 0 CodeIncrement <- 0 LastBitLength <- 0 i <- number of Shannon-Fano codes - 1 (either 255 or 63) loop while i >= 0 Code = Code + CodeIncrement if BitLength(i) <> LastBitLength then LastBitLength=BitLength(i) CodeIncrement = 1 shifted left (16 - LastBitLength) ShannonCode(i) = Code i <- i - 1 end loop ``` -------------------------------- ### toBuffer Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Converts the current zip archive into a Buffer object. This method supports callbacks for success, failure, and item processing. ```APIDOC ## toBuffer(onSuccess, onFail, onItemStart, onItemEnd) ### Description Converts the current zip archive into a Buffer object. This method supports callbacks for success, failure, and item processing. ### Parameters #### Path Parameters - **onSuccess** (Function) - Optional - Callback function executed upon successful conversion. - **onFail** (Function) - Optional - Callback function executed if conversion fails. - **onItemStart** (Function) - Optional - Callback function executed when processing of an item starts. - **onItemEnd** (Function) - Optional - Callback function executed when processing of an item ends. ### Returns - **Buffer** - The zip archive as a Buffer object. ``` -------------------------------- ### addLocalFolder Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Adds a local directory and all its contents (files and subdirectories) to the zip archive. ```APIDOC ## addLocalFolder(localPath, zipPath) ### Description Adds a local directory and all its contents (files and subdirectories) to the zip archive. ### Parameters #### Path Parameters - **localPath** (String) - Required - The path to the local directory to add. - **zipPath** (String) - Required - The desired path for the directory within the zip archive. ### Returns - **void** ``` -------------------------------- ### addLocalFile Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Adds a file from the local file system to the zip archive. ```APIDOC ## addLocalFile(localPath, zipPath) ### Description Adds a file from the local file system to the zip archive. ### Parameters #### Path Parameters - **localPath** (String) - Required - The path to the local file to add. - **zipPath** (String) - Required - The desired path for the file within the zip archive. ### Returns - **void** ``` -------------------------------- ### extractAllTo Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Extracts the entire contents of the zip archive to a specified target path. Supports overwriting existing files. ```APIDOC ## extractAllTo ### Description Extracts all entries from the archive to the specified target path. Existing files can be overwritten. ### Method Signature `extractAllTo(String targetPath, Boolean overwrite = false)` ### Parameters * **targetPath** (String) - The directory path where the entire archive will be extracted. * **overwrite** (Boolean, optional) - Defaults to `false`. If true, overwrites existing files at the target path. ### Examples ```javascript // Extract all files to '/home/user/extracted_files/' overwriting existing files zip.extractAllTo("/home/user/extracted_files/", true); // Extract all files to '/home/user/extracted_files/' without overwriting zip.extractAllTo("/home/user/extracted_files/"); ``` ``` -------------------------------- ### getEntry Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Retrieves a specific entry from the zip archive by its name. ```APIDOC ## getEntry(name) ### Description Retrieves a specific entry from the zip archive by its name. ### Parameters #### Path Parameters - **name** (String) - Required - The name of the entry to retrieve. ### Returns - **ZipObject** - The ZipEntry object corresponding to the given name. ``` -------------------------------- ### readFileAsync Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Asynchronously extracts the content of a specified entry from the archive and returns it as a Buffer via a callback. ```APIDOC ## readFileAsync(entry, callback) ### Description Asynchronously extracts the content of a specified entry from the archive and returns it as a Buffer via a callback. ### Parameters #### Path Parameters - **entry** (ZipEntry or String) - Required - The entry to read. Can be a ZipEntry object or its name. - **callback** (Function) - Required - The callback function to execute with the Buffer content. ### Returns - **void** ``` -------------------------------- ### writeZip Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Writes the current state of the zip archive to a file on the local file system. ```APIDOC ## writeZip(targetFileName) ### Description Writes the current state of the zip archive to a file on the local file system. ### Parameters #### Path Parameters - **targetFileName** (String) - Required - The name of the file to write the zip archive to. ### Returns - **void** ``` -------------------------------- ### Clone adm-zip from GitHub Source: https://github.com/cthackers/adm-zip/wiki/How-to-Install Clone the adm-zip repository directly from GitHub using git. This method is useful for development or if you need the latest code. ```bash $ git clone git://github.com/cthackers/adm-zip.git ``` -------------------------------- ### Write ZIP to Disk Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Saves the current state of the ZIP archive to a file. If a `targetFileName` is provided, the archive is written to that location. If no `targetFileName` is specified, the original ZIP file (if one was opened) will be overwritten. ```javascript zip.writeZip("/path/to/new/archive.zip"); ``` -------------------------------- ### ZipEntry Methods Source: https://github.com/cthackers/adm-zip/wiki/ZipEntry Methods available on the ZipEntry class for manipulating and retrieving zip entry information. ```APIDOC ## ZipEntry Methods ### packHeader() - **Description**: Returns the CEN Entry Header to be written in the output zip file, including any extra data and the entry comment. - **Returns**: Buffer (CEN Entry Header) ### toString() - **Description**: Returns a string representation of the ZipEntry, summarizing its most important properties. - **Returns**: String ``` -------------------------------- ### updateFile Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Updates the content of an existing entry in the zip archive. The archive must be rewritten after the update. ```APIDOC ## updateFile(entry, content) ### Description Updates the content of an existing entry in the zip archive. The archive must be rewritten after the update. ### Parameters #### Path Parameters - **entry** (ZipEntry or String) - Required - The entry to update. Can be a ZipEntry object or its name. - **content** (Buffer) - Required - The new content for the entry. ### Returns - **void** ``` -------------------------------- ### readFile Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Extracts the content of a specified entry from the archive and returns it as a Buffer. ```APIDOC ## readFile(entry) ### Description Extracts the content of a specified entry from the archive and returns it as a Buffer. ### Parameters #### Path Parameters - **entry** (ZipEntry or String) - Required - The entry to read. Can be a ZipEntry object or its name. ### Returns - **Buffer** - The content of the entry as a Buffer. ``` -------------------------------- ### getEntry(String entryName) Source: https://github.com/cthackers/adm-zip/wiki/ZipFile Retrieves a specific entry from the archive by its name. ```APIDOC ## getEntry(String entryName) ### Description Returns a reference to the entry with the given `entryName` or null if entry is inexistent. ### Method GET (conceptual) ### Endpoint N/A (Method call on ZipFile object) ### Parameters #### Path Parameters - **entryName** (String) - Required - The name of the entry to retrieve. ### Returns - **ZipEntry** - A reference to the ZipEntry object if found. - **null** - If the entry with the specified name does not exist. ``` -------------------------------- ### Extract All Entries to Target Path Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Extracts all contents of the archive to the specified target directory. The `overwrite` parameter determines if existing files at the target path should be replaced. ```javascript zip.extractAllTo("/home/user/extracted_files/", true); ``` -------------------------------- ### getEntries Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Retrieves all entries (files and folders) contained within the zip archive. ```APIDOC ## getEntries() ### Description Retrieves all entries (files and folders) contained within the zip archive. ### Method GET ### Endpoint /entries ### Returns - **Array** - An array of ZipEntry objects. ``` -------------------------------- ### writeZip Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Writes the zip archive to disk. If a target file name is provided, it writes to that location; otherwise, it overwrites the currently opened zip file. ```APIDOC ## writeZip ### Description Writes the contents of the zip archive to disk. Can specify a new file path or overwrite the existing one. ### Method Signature `writeZip(String targetFileName)` ### Parameters * **targetFileName** (String) - The path where the zip file should be saved. If omitted, the original zip file is overwritten. ### Examples ```javascript // Write the zip to a new file named 'backup.zip' zip.writeZip("backup.zip"); // Overwrite the currently opened zip file zip.writeZip(); ``` ``` -------------------------------- ### extractEntryTo Source: https://github.com/cthackers/adm-zip/wiki/ADM-ZIP Extracts a specific entry from the zip archive to a target path. Supports maintaining entry path structure and overwriting existing files. ```APIDOC ## extractEntryTo ### Description Extracts the given entry to the specified target path. Can optionally maintain the entry's original path structure and overwrite existing files. ### Method Signature `extractEntryTo(Object entry, String targetPath, Boolean maintainEntryPath = true, Boolean overwrite = false, String outFileName)` ### Parameters * **entry** (Object | String) - The zip entry object or its name to extract. * **targetPath** (String) - The directory path where the entry will be extracted. * **maintainEntryPath** (Boolean, optional) - Defaults to `true`. If true, creates parent directories for the entry if it's nested. * **overwrite** (Boolean, optional) - Defaults to `false`. If true, overwrites existing files at the target path. * **outFileName** (String, optional) - If provided, the extracted file will be renamed to this value. ### Examples ```javascript // Extract 'folder/subfolder/myfile.txt' to '/home/user/' maintaining path structure and overwriting zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", true, true); // Extract 'folder/subfolder/myfile.txt' to '/home/user/' without maintaining path structure zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true); // Extract 'folder/subfolder/myfile.txt' to '/home/user/' and rename it to 'newname.txt' zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true, "newname.txt"); ``` ``` -------------------------------- ### getEntryChildren(ZipEntry entry) Source: https://github.com/cthackers/adm-zip/wiki/ZipFile Retrieves all nested files and directories within a given entry. ```APIDOC ## getEntryChildren(ZipEntry entry) ### Description Iterates and returns all nested files and directories of the given `entry`. ### Method GET (conceptual) ### Endpoint N/A (Method call on ZipFile object) ### Parameters #### Request Body - **entry** (ZipEntry) - Required - The parent entry for which to retrieve children. ### Returns - **Array** - An array of ZipEntry objects representing the children of the given entry. ``` -------------------------------- ### entries Source: https://github.com/cthackers/adm-zip/wiki/ZipFile Retrieves an array of ZipEntry objects representing all entries within the opened archive. ```APIDOC ## entries ### Description Returns an array of ZipEntry objects existent in the current opened archive. ### Method GET (conceptual) ### Endpoint N/A (Method call on ZipFile object) ### Returns - **Array** - An array of ZipEntry objects. ```