archiver

repository·master·Indexed 25 days ago

https://github.com/archiverjs/node-archiver

A streaming interface for generating archive files in Node.js, supporting ZIP, TAR (including GZIP), and JSON formats. It allows developers to create archives by piping data to writable streams and provides methods to append files, directories, and globs, as well as the ability to register custom archive formats.

Tokens
4.3K
Snippets
8
Records
23
Agent score
84%

What's inside archiver

  1. Create a basic ZIP archive

    master

    To create an archive, initialize archiver with a format (e.g., 'zip'), pipe it to a writable stream (like a file stream), append files or directories, and call .finalize().

    It is recommended to listen for the warning and error events on the archive instance to handle non-blocking errors (like ENOENT) and critical failures. You should also listen for the close event on the output stream to know when the file has been fully written to disk.

    // 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.
    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)
    archive.finalize();
  2. Quick Start with Archiver

    master

    Archiver provides a streaming interface for generating archives. To use it, create an archive instance (e.g., ZipArchive), pipe it to a writable stream (like a file stream), append files or directories using various methods, and finally call .finalize() to complete the process.

    It is recommended to listen for warning and error events on the archive instance, and close or end events on the output stream to handle completion and potential issues.

    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();
  3. Configure Archiver core and format options

    master

    The options object passed to the Archiver constructor supports several configuration keys:

    Core Options

    • statConcurrency: (Number, default: 4) Sets the number of workers used to process the internal fs stat queue.

    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.

    Note: For additional TAR properties, refer to the tar-stream documentation.

  4. Append files, directories, and globs to an archive

    master

    Use the following methods to add content to your archive. Most methods accept an optional data object of type Entry Data.

    • append(source, data): Appends a text string, Buffer, or Stream.
    • file(filepath, data): Appends a file from a specific path using a lazy-stream wrapper to manage open file limits.
    • directory(dirpath, destpath, data): Recursively appends a directory from dirpath to destpath within the archive.
    • glob(pattern, options, data): Appends multiple files matching a glob pattern. options can include a cwd property.
    • symlink(filepath, target, mode): Programmatically creates a symlink within the archive (does not interact with the actual filesystem).
  5. Configure ZipStream constructor options

    master

    When instantiating a new ZipStream, you can provide an options object to configure the archive behavior. Supported properties include:

    • 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 the Node.js zlib module to control compression.
    new ZipStream(options);