### Example 10: Add String Content Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create files from string content by adding buffers to the ZipFile. ```javascript var yazl = require("yazl"); var fs = require("fs"); var zipfile = new yazl.ZipFile(); zipfile.addBuffer( Buffer.from("Hello, World!"), "hello.txt" ); zipfile.addBuffer( Buffer.from(JSON.stringify({version: "1.0.0"}, null, 2)), "package.json" ); zipfile.addBuffer( Buffer.from("# My Project\n\nThis is a test."), "README.md" ); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("generated.zip")); ``` -------------------------------- ### Comprehensive Configuration Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/configuration.md An example demonstrating how to use various configuration options when creating a zip file with Yazl. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); // File with all options specified zipfile.addFile("readme.txt", "README.txt", { mtime: new Date(2024, 0, 1), mode: 0o100644, compress: true, compressionLevel: 9, forceZip64Format: false, forceDosTimestamp: false, fileComment: "Main readme file" }); // File with minimal options zipfile.addFile("data.json", "data.json"); // Buffer with options var data = fs.readFileSync("config.json"); zipfile.addBuffer(data, "config.json", { compress: false, fileComment: "Configuration file" }); // Stream with size for total size calculation zipfile.addReadStreamLazy("large-file.bin", { size: 1024 * 1024 * 100, // 100 MB compress: true, compressionLevel: 6 }, function(callback) { callback(null, fs.createReadStream("large-file.bin")); }); // Directory structure zipfile.addEmptyDirectory("src/"); zipfile.addEmptyDirectory("docs/"); // Finalize with archive options and callback zipfile.end({ forceZip64Format: false, comment: "Archive created by MyApp v1.0" }, function(totalSize) { console.log("Total size: " + (totalSize === -1 ? "unknown" : totalSize) + " bytes"); }); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Example Variants Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Various examples demonstrating different use cases and options for the addBuffer method. ```javascript // Variant 1: Simple text buffer var content = Buffer.from("Hello, World!"); zipfile.addBuffer(content, "greeting.txt"); ``` ```javascript // Variant 2: Compressed JSON var data = Buffer.from(JSON.stringify({key: "value"}, null, 2)); zipfile.addBuffer(data, "config.json", {compress: true}); ``` ```javascript // Variant 3: Uncompressed binary (for compatibility) var binaryData = Buffer.from([0x89, 0x50, 0x4e, 0x47]); zipfile.addBuffer(binaryData, "header.bin", {compress: false}); ``` ```javascript // Variant 4: Maximum compression for text var largeText = Buffer.alloc(1000000, "Hello\n"); zipfile.addBuffer(largeText, "large.txt", { compressionLevel: 9 }); ``` ```javascript // Variant 5: With custom timestamp and permissions var content = Buffer.from("data"); zipfile.addBuffer(content, "data.txt", { mtime: new Date(2024, 0, 1), mode: 0o100644, compress: false }); ``` ```javascript // Variant 6: With file comment zipfile.addBuffer(content, "data.txt", { fileComment: "Generated data" }); ``` -------------------------------- ### Example Variants Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Various examples demonstrating different use cases and configurations of the addEmptyDirectory method. ```javascript // Variant 1: Simple directory zipfile.addEmptyDirectory("src/"); ``` ```javascript // Variant 2: Without trailing slash (auto-added) zipfile.addEmptyDirectory("docs"); // Becomes "docs/" ``` ```javascript // Variant 3: Custom timestamp zipfile.addEmptyDirectory("archive/", { mtime: new Date(2024, 0, 1) }); ``` ```javascript // Variant 4: Custom permissions zipfile.addEmptyDirectory("private/", { mode: 0o40700 // drwx------ }); ``` ```javascript // Variant 5: DOS timestamp only (old format) zipfile.addEmptyDirectory("old/", { forceDosTimestamp: true }); ``` ```javascript // Variant 6: Create directory structure ["bin/", "src/", "test/", "docs/"].forEach(function(dir) { zipfile.addEmptyDirectory(dir, { mode: 0o40775 }); }); ``` -------------------------------- ### end() Options Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/configuration.md Example of using the end() method with archive-level options. ```javascript zipfile.end({ comment: "Created by MyApp v1.0", forceZip64Format: false }); ``` -------------------------------- ### Example 13: Download with Size Prediction Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Use calculatedTotalSizeCallback to set the Content-Length header when serving a ZIP. ```javascript var express = require("express"); var yazl = require("yazl"); var fs = require("fs"); app.get("/files", function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("ZIP error:", err); if (!res.headersSent) { res.status(500).send("Error"); } }); res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", "attachment; filename=files.zip"); // Add uncompressed files for size prediction zipfile.addFile("file1.txt", "file1.txt", {compress: false}); zipfile.addFile("file2.txt", "file2.txt", {compress: false}); zipfile.end({forceZip64Format: false}, function(totalSize) { if (totalSize !== -1) { // Size is known because no compression res.setHeader("Content-Length", totalSize); } }); zipfile.outputStream.pipe(res); }); ``` -------------------------------- ### Example 12: Download ZIP in Express Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Serve a ZIP archive from an Express.js endpoint. ```javascript var express = require("express"); var yazl = require("yazl"); var fs = require("fs"); var app = express(); app.get("/download", function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("ZIP error:", err); res.status(500).send("Failed to create archive"); }); res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", "attachment; filename=archive.zip"); // Add files zipfile.addFile("file1.txt", "file1.txt"); zipfile.addFile("file2.txt", "file2.txt"); zipfile.end(function(totalSize) { if (totalSize !== -1) { res.setHeader("Content-Length", totalSize); } }); zipfile.outputStream.pipe(res); }); app.listen(3000); ``` -------------------------------- ### Example Variants Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Examples demonstrating different variants of using the addReadStream method. ```javascript // Variant 1: Simple stream add var stream = fs.createReadStream("data.json"); zipfile.addReadStream(stream, "data.json"); ``` ```javascript // Variant 2: With known size for pre-calculation var stats = fs.statSync("largefile.bin"); zipfile.addReadStream( fs.createReadStream("largefile.bin"), "largefile.bin", {size: stats.size} ); ``` ```javascript // Variant 3: Uncompressed with size zipfile.addReadStream( fs.createReadStream("video.mp4"), "video.mp4", {size: 1024*1024*100, compress: false} ); ``` ```javascript // Variant 4: With custom timestamp zipfile.addReadStream( fs.createReadStream("archive.tar"), "archive.tar", { mtime: new Date(2024, 0, 1), size: 5000000 } ); ``` -------------------------------- ### Example 11: Generate Dynamic Content Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create a ZIP archive with dynamically generated files based on data. ```javascript var yazl = require("yazl"); var fs = require("fs"); function generateReport(data) { return "Report Generated\n" + "Date: " + new Date().toISOString() + "\n" + "Data: " + JSON.stringify(data) + "\n"; } var zipfile = new yazl.ZipFile(); // Generate multiple files from data var datasets = ["users", "products", "orders"]; datasets.forEach(function(dataset) { var content = generateReport({dataset: dataset}); zipfile.addBuffer( Buffer.from(content), dataset + "-report.txt" ); }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("reports.zip")); ``` -------------------------------- ### Example 15: Validation Before Adding Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Validate file paths before adding them to the ZIP archive to prevent security issues. ```javascript var fs = require("fs"); var yazl = require("yazl"); function isValidZipPath(path) { // Check for empty path if (!path || path.length === 0) return false; // Check for absolute paths if (path[0] === "/" || /^[a-z]:/i.test(path)) return false; // Check for parent directory references if (path.indexOf("..") !== -1) return false; return true; } var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("ZIP error:", err.message); }); var files = [ {source: "file1.txt", dest: "file1.txt"}, {source: "file2.txt", dest: "/absolute/path.txt"}, // Invalid {source: "file3.txt", dest: "path/../file3.txt"} // Invalid ]; files.forEach(function(file) { try { if (!isValidZipPath(file.dest)) { console.warn("Skipping invalid path:", file.dest); return; } zipfile.addFile(file.source, file.dest); } catch (err) { console.error("Error adding file:", err.message); } }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Installation Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md Install the yazl package using npm. ```bash npm install yazl ``` -------------------------------- ### Multiple Files Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create a ZIP with multiple files in different directories. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("src/index.js", "src/index.js"); zipfile.addFile("src/lib.js", "src/lib.js"); zipfile.addFile("README.md", "README.md"); zipfile.addFile("package.json", "package.json"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("myapp.zip")); ``` -------------------------------- ### Minimal Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md A minimal example demonstrating how to create a ZIP archive with a single file. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Minimal Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/Exports.md A basic example demonstrating how to create a zip file with a single file. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Async/Await Pattern Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Demonstrates using modern async/await syntax for a cleaner asynchronous ZIP creation workflow. ```javascript var fs = require("fs"); var util = require("util"); var yazl = require("yazl"); var writeFile = util.promisify(fs.writeFile); var pipeline = util.promisify(require("stream").pipeline); async function createZipAsync(files, outputPath) { var zipfile = new yazl.ZipFile(); return new Promise(function(resolve, reject) { zipfile.on("error", reject); files.forEach(function(file) { try { zipfile.addFile(file.source, file.dest); } catch (err) { reject(err); return; } }); zipfile.end(); var writeStream = fs.createWriteStream(outputPath); writeStream.on("error", reject); writeStream.on("finish", function() { resolve(outputPath); }); zipfile.outputStream.pipe(writeStream); }); } // Usage (async function() { try { var path = await createZipAsync([ {source: "file1.txt", dest: "file1.txt"}, {source: "file2.txt", dest: "file2.txt"} ], "archive.zip"); console.log("ZIP created:", path); } catch (err) { console.error("Error:", err.message); } })(); ``` -------------------------------- ### Full Example: Creating and Ending a ZipFile Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md A comprehensive example showing how to create a ZipFile, add files and buffers, and then end the archive with a comment and a size callback. ```javascript var yazl = require("yazl"); var fs = require("fs"); var http = require("http"); var zipfile = new yazl.ZipFile(); zipfile.addFile("app.js", "app.js", {compress: false}); zipfile.addBuffer(Buffer.from("data"), "data.txt", {compress: false}); zipfile.end({comment: "App v1.0"}, function(totalSize) { if (totalSize === -1) { console.log("Size: unknown"); } else { console.log("Size: " + totalSize + " bytes"); } }); // Use in HTTP response var server = http.createServer(function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(function(totalSize) { if (totalSize !== -1) { res.setHeader("Content-Length", totalSize); } }); zipfile.outputStream.pipe(res); }); ``` -------------------------------- ### Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Example of using addReadStream. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); var fileSize = fs.statSync("document.pdf").size; zipfile.addReadStream( fs.createReadStream("document.pdf"), "docs/document.pdf", { size: fileSize, compress: true } ); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Usage Example Source: https://github.com/thejoshwolfe/yazl/blob/master/README.md Demonstrates how to create a zip file, add files, and pipe the output stream. ```javascript var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("file1.txt", "file1.txt"); // (add only files, not directories) zipfile.addFile("path/to/file.txt", "path/in/zipfile.txt"); // pipe() can be called any time after the constructor zipfile.outputStream.pipe(fs.createWriteStream("output.zip")).on("close", function() { console.log("done"); }); // alternate apis for adding files: zipfile.addBuffer(Buffer.from("hello"), "hello.txt"); zipfile.addReadStreamLazy("stdin.txt", cb => cb(null, process.stdin)); // call end() after all the files have been added zipfile.end(); ``` -------------------------------- ### File Path Validation Examples Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/configuration.md Illustrates valid and invalid file path examples for Yazl entries, covering various rules like absolute paths, parent references, and trailing slashes. ```javascript // Valid zipfile.addFile("file.txt", "file.txt"); zipfile.addFile("file.txt", "path/to/file.txt"); zipfile.addFile("file.txt", "path\with\backslashes.txt"); // Backslashes converted to / // Invalid zipfile.addFile("file.txt", ""); // Error: empty zipfile.addFile("file.txt", "/absolute/path.txt"); // Error: starts with / zipfile.addFile("file.txt", "C:/path.txt"); // Error: Windows absolute zipfile.addFile("file.txt", "path/../file.txt"); // Error: contains .. zipfile.addFile("file.txt", "dir/"); // Error: file path ends with / ``` -------------------------------- ### Example Variants for addFile() Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Demonstrates various ways to use the addFile method with different options. ```javascript // Variant 1: Compressed with defaults zipfile.addFile("src/index.js", "src/index.js"); // Variant 2: No compression zipfile.addFile("large.bin", "large.bin", {compress: false}); // Variant 3: Maximum compression zipfile.addFile("text.txt", "text.txt", {compressionLevel: 9}); // Variant 4: No compression via compressionLevel zipfile.addFile("data.json", "data.json", {compressionLevel: 0}); // Variant 5: Custom timestamp zipfile.addFile("file.txt", "file.txt", { mtime: new Date(2024, 0, 1) }); // Variant 6: Custom permissions zipfile.addFile("script.sh", "script.sh", { mode: 0o100755 // -rwxr-xr-x }); // Variant 7: Multiple options combined zipfile.addFile("archive/data.csv", "data/archive.csv", { compress: true, compressionLevel: 9, mtime: new Date(), mode: 0o100644, fileComment: "Raw data export" }); ``` -------------------------------- ### Example 14: Basic Error Handling Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Handle errors that occur during the ZIP creation process. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("Failed to create ZIP:", err.message); // Clean up if needed process.exit(1); }); try { zipfile.addFile("file.txt", "file.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("output.zip")); } catch (err) { console.error("Setup error:", err.message); process.exit(1); } ``` -------------------------------- ### Using addReadStream Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Add files from streams directly. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addReadStream( fs.createReadStream("large-file.bin"), "large-file.bin", {size: 1024 * 1024 * 100, compress: false} // 100 MB ); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Example Variants of `end()` Calls Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Illustrates various practical examples of calling the `end()` method with different combinations of options and callbacks. ```javascript // Variant 1: Simple end, no options zipfile.end(); // Variant 2: With callback only zipfile.end(function(size) { console.log("Total size: " + size); }); // Variant 3: With options only zipfile.end({ comment: "Created by MyApp", forceZip64Format: false }); // Variant 4: With both options and callback zipfile.end({ comment: "Archive v1.0", forceZip64Format: false }, function(size) { console.log("Size: " + (size === -1 ? "unknown" : size)); }); // Variant 5: Options as first param, callback implicit (if function) zipfile.end(function(size) { // This is treated as callback, not options console.log("Size: " + size); }); // Variant 6: Setup for HTTP response zipfile.end({comment: "API Export"}, function(totalSize) { if (totalSize !== -1) { res.setHeader("Content-Length", totalSize); } }); ``` -------------------------------- ### Stream from stdin Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Read from standard input. ```javascript var yazl = require("yazl"); var fs = require("fs"); var zipfile = new yazl.ZipFile(); zipfile.addReadStream(process.stdin, "input.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("output.zip")); ``` -------------------------------- ### addEmptyDirectory Full Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md A complete example demonstrating the creation of a ZIP archive with empty directories and files. ```javascript var yazl = require("yazl"); var fs = require("fs"); var zipfile = new yazl.ZipFile(); zipfile.addEmptyDirectory("bin/"); zipfile.addEmptyDirectory("src/"); zipfile.addEmptyDirectory("docs/", { mode: 0o40755, mtime: new Date() }); zipfile.addFile("index.js", "index.js"); zipfile.addFile("readme.txt", "readme.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("project.zip")); ``` -------------------------------- ### Include Directory Structure Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Preserve directory structure using relative paths. ```javascript var fs = require("fs"); var path = require("path"); var yazl = require("yazl"); var rootDir = "app"; var zipfile = new yazl.ZipFile(); // Add directories zipfile.addEmptyDirectory("src/"); zipfile.addEmptyDirectory("docs/"); zipfile.addEmptyDirectory("test/"); // Add files maintaining structure zipfile.addFile(path.join(rootDir, "index.js"), "index.js"); zipfile.addFile(path.join(rootDir, "src/app.js"), "src/app.js"); zipfile.addFile(path.join(rootDir, "docs/api.md"), "docs/api.md"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("app.zip")); ``` -------------------------------- ### Simple File ZIP Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create a ZIP with a single file. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("README.md", "README.md"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### addBuffer Full Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md A comprehensive example showing how to add JSON configuration and binary image data to a ZIP archive using addBuffer. ```javascript var yazl = require("yazl"); var fs = require("fs"); var zipfile = new yazl.ZipFile(); // JSON configuration var configBuffer = Buffer.from(JSON.stringify({ version: "1.0.0", name: "MyApp" }, null, 2)); zipfile.addBuffer(configBuffer, "config.json", {compress: false}); // Binary data var binaryData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); zipfile.addBuffer(binaryData, "image.png", {compress: true}); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Promise-Wrapped ZIP Creation Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Shows how to wrap the ZIP creation process in a JavaScript Promise for easier asynchronous handling. ```javascript var fs = require("fs"); var yazl = require("yazl"); function createZip(files, outputPath) { return new Promise(function(resolve, reject) { var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { reject(new Error("ZIP creation failed: " + err.message)); }); try { files.forEach(function(file) { zipfile.addFile(file.source, file.dest, file.options); }); } catch (err) { reject(new Error("Invalid file: " + err.message)); return; } zipfile.end(); var writeStream = fs.createWriteStream(outputPath); writeStream.on("error", function(err) { reject(new Error("Write failed: " + err.message)); }); writeStream.on("finish", function() { resolve(outputPath); }); zipfile.outputStream.pipe(writeStream); }); } // Usage createZip([ {source: "file1.txt", dest: "file1.txt"}, {source: "file2.txt", dest: "file2.txt"} ], "archive.zip") .then(function(path) { console.log("ZIP created:", path); }) .catch(function(err) { console.error(err.message); }); ``` -------------------------------- ### Mixed Compression Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Use different compression levels per file. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); // Text: maximum compression zipfile.addFile("readme.txt", "readme.txt", {compressionLevel: 9}); // Images: no compression (already compressed) zipfile.addFile("logo.png", "logo.png", {compress: false}); zipfile.addFile("photo.jpg", "photo.jpg", {compress: false}); // Code: balanced compression zipfile.addFile("app.js", "app.js", {compressionLevel: 6}); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("mixed.zip")); ``` -------------------------------- ### Full Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md A complete example showing how to use addReadStreamLazy to add multiple files to a ZIP archive. ```javascript var yazl = require("yazl"); var fs = require("fs"); var zipfile = new yazl.ZipFile(); // Lazy stream opening - file not opened until needed zipfile.addReadStreamLazy("config.json", {compress: true}, function(callback) { // This function runs when the entry is ready to be written var stream = fs.createReadStream("config.json"); callback(null, stream); }); zipfile.addReadStreamLazy("app.js", function(callback) { var stream = fs.createReadStream("app.js"); callback(null, stream); }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("app.zip")); ``` -------------------------------- ### Using addReadStreamLazy (Recommended) Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Add files lazily to avoid holding file handles open. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); // Add multiple files without holding all handles open var files = ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]; files.forEach(function(filename) { zipfile.addReadStreamLazy(filename, function(cb) { var stream = fs.createReadStream(filename); cb(null, stream); }); }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Maximum Compression Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create ZIP with maximum compression for text/code. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("large-text.txt", "large-text.txt", { compressionLevel: 9 }); zipfile.addFile("source.js", "source.js", { compressionLevel: 9 }); zipfile.addFile("data.json", "data.json", { compressionLevel: 9 }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("compressed.zip")); ``` -------------------------------- ### Adding File Comments Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Includes metadata comments with individual files and a general comment for the entire archive. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("readme.txt", "readme.txt", { fileComment: "Main readme file" }); zipfile.addFile("config.json", "config.json", { fileComment: "Configuration - do not edit" }); zipfile.addFile("data.csv", "data.csv", { fileComment: "Raw data export - 2024-01-15" }); zipfile.end({ comment: "Archive created by MyApp v1.0" }); zipfile.outputStream.pipe(fs.createWriteStream("documented.zip")); ``` -------------------------------- ### Selective File Addition Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Adds files to a zip archive based on specified extensions and ignore patterns. ```javascript var fs = require("fs"); var path = require("path"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("ZIP error:", err.message); }); // File filters var extensions = [".js", ".json", ".md"]; var ignorePatterns = ["node_modules", ".git", "dist"]; function shouldInclude(filePath) { // Check extension var ext = path.extname(filePath); if (extensions.indexOf(ext) === -1) return false; // Check ignore patterns for (var i = 0; i < ignorePatterns.length; i++) { if (filePath.indexOf(ignorePatterns[i]) !== -1) { return false; } } return true; } // Process files var files = ["index.js", "lib.js", "config.json", "README.md", "node_modules/pkg/index.js", ".git/config"]; files.forEach(function(file) { if (shouldInclude(file)) { zipfile.addFile(file, file); } }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("filtered.zip")); ``` -------------------------------- ### outputStream Usage Examples Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Demonstrates how to pipe the outputStream to a file or an HTTP response. ```javascript var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(); // Pipe to file zipfile.outputStream.pipe(fs.createWriteStream("output.zip")); // Or pipe to HTTP response app.get("/download", function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.addFile("report.txt", "report.txt"); zipfile.end(); res.setHeader("Content-Type", "application/zip"); zipfile.outputStream.pipe(res); }); ``` -------------------------------- ### Batch File Processing Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Recursively processes a directory and adds all its files and subdirectories to a zip archive. ```javascript var fs = require("fs"); var path = require("path"); var yazl = require("yazl"); function zipDirectory(sourceDir, outputFile) { var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("ZIP error:", err.message); }); // Recursively process directory function processDir(dir, zipPath) { var files = fs.readdirSync(dir); files.forEach(function(file) { var fullPath = path.join(dir, file); var stats = fs.statSync(fullPath); var arcPath = path.join(zipPath, file).replace(/\\/g, "/"); if (stats.isDirectory()) { zipfile.addEmptyDirectory(arcPath + "/"); processDir(fullPath, arcPath); } else { zipfile.addFile(fullPath, arcPath); } }); } processDir(sourceDir, ""); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream(outputFile)); } zipDirectory("./app", "app.zip"); ``` -------------------------------- ### Disable Compression Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Create uncompressed ZIP (useful for already-compressed files or testing). ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("image.jpg", "image.jpg", {compress: false}); zipfile.addFile("video.mp4", "video.mp4", {compress: false}); zipfile.addFile("archive.tar.gz", "archive.tar.gz", {compress: false}); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("media.zip")); ``` -------------------------------- ### Task: Create ZIP of Directory Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md Example of recursively adding all files and directories from a local directory into a ZIP archive. ```javascript var fs = require("fs"); var path = require("path"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); function addDir(dir, arcPath) { fs.readdirSync(dir).forEach(function(file) { var full = path.join(dir, file); var arc = path.join(arcPath, file).replace(/\\/g, "/"); if (fs.statSync(full).isDirectory()) { zipfile.addEmptyDirectory(arc + "/"); addDir(full, arc); } else { zipfile.addFile(full, arc); } }); } addDir(".", ""); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### addBuffer Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Demonstrates how to add content from a Buffer to the ZIP archive, with and without compression options. ```javascript var content = Buffer.from("Hello, World!"); zipfile.addBuffer(content, "hello.txt"); zipfile.addBuffer(content, "compressed.txt", { compress: true, compressionLevel: 9, mtime: new Date() }); ``` -------------------------------- ### Error Handling Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md Demonstrates how to listen for asynchronous error events emitted by Yazl. ```javascript zipfile.on("error", function(err) { console.error("ZIP creation failed:", err.message); }); ``` -------------------------------- ### addFile Usage Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Demonstrates adding files to a ZipFile and piping the output to a write stream. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.addFile("app.js", "src/app.js"); zipfile.addFile("config.json", "config.json", { compress: false, mtime: new Date(2024, 0, 1) }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### addFile Method Examples Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Adds a file from the filesystem into the ZIP archive with basic and advanced options. ```javascript zipfile.addFile("path/to/file.txt", "archive/path.txt"); zipfile.addFile("readme.txt", "README.txt", { compress: true, compressionLevel: 6, mtime: new Date() }); ``` -------------------------------- ### ZipFile Class Usage Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/Exports.md Basic usage example for creating a new ZipFile instance. ```javascript var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); ``` -------------------------------- ### end() method examples Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/ZipFile.md Demonstrates various ways to call the end() method with different options and callbacks. ```javascript zipfile.end(); zipfile.end({comment: "My Archive"}); zipfile.end({forceZip64Format: true}, function(size) { console.log("Total ZIP size: " + size + " bytes"); }); zipfile.end(function(size) { if (size === -1) { console.log("Size unknown (compression used)"); } else { console.log("Total ZIP size: " + size + " bytes"); } }); ``` -------------------------------- ### With Error Handling Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/Exports.md An example showing how to implement error handling for zip file operations. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("Failed:", err.message); }); try { zipfile.addFile("file.txt", "file.txt"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); } catch (err) { console.error("Setup error:", err.message); } ``` -------------------------------- ### Task: Get Predicted ZIP Size Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md Example of how to get the total size of the ZIP archive after it has been finalized, with a callback for the size. ```javascript var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt", {compress: false}); zipfile.end(function(totalSize) { if (totalSize === -1) { console.log("Size unknown (compression used)"); } else { console.log("Total size: " + totalSize + " bytes"); } }); ``` -------------------------------- ### addReadStreamLazy Example Source: https://github.com/thejoshwolfe/yazl/blob/master/README.md Example call to addReadStreamLazy to add a file from a read stream. ```javascript zipfile.addReadStreamLazy("path/in/archive.txt", function(cb) { var readStream = getTheReadStreamSomehow(); cb(null, readStream); }); ``` -------------------------------- ### dateToDosDateTime Function Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/Exports.md Example demonstrating the usage and output of the deprecated dateToDosDateTime function. ```javascript var yazl = require("yazl"); var result = yazl.dateToDosDateTime(new Date(2024, 0, 15, 14, 30, 45)); console.log(result); // Output: {date: 21513, time: 29381} ``` -------------------------------- ### Constructor Defaults Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/configuration.md Shows the default initialization values when creating a new ZipFile instance without any parameters. ```javascript new ZipFile() // No parameters; initializes with: // { // outputStream: new PassThrough(), // entries: [], // ended: false, // errored: false // } ``` -------------------------------- ### Size Mismatch Error Example Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/errors.md Shows an example where addReadStream() or addReadStreamLazy() is used with a size option that does not match the actual bytes read from the stream. ```javascript var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error(err.message); // "file data stream has unexpected number of bytes" }); var data = Buffer.from("Hello"); zipfile.addReadStreamLazy("file.txt", {size: 10}, function(cb) { // Actual stream has 5 bytes, but size is 10 cb(null, new (require("stream").Readable)({ read() { this.push(data); this.push(null); } })); }); ``` -------------------------------- ### With All File Methods Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/Exports.md Demonstrates various methods for adding files to a zip archive, including from filesystem, streams (immediate and lazy), buffers, and empty directories. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); // From filesystem zipfile.addFile("local-file.txt", "file1.txt"); // From stream (immediate) zipfile.addReadStream(fs.createReadStream("stdin.txt"), "file2.txt"); // From stream (lazy - recommended) zipfile.addReadStreamLazy("file3.txt", function(cb) { cb(null, fs.createReadStream("source.txt")); }); // From buffer zipfile.addBuffer(Buffer.from("content"), "file4.txt"); // Empty directory zipfile.addEmptyDirectory("folder/"); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("archive.zip")); ``` -------------------------------- ### Example Variants Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Demonstrates various ways to use the addReadStreamLazy method, including simple streams, streams with options, streams with pre-calculated size, error handling, and multiple file additions. ```javascript // Variant 1: Simple lazy stream without options zipfile.addReadStreamLazy("file.txt", function(cb) { var stream = fs.createReadStream("source.txt"); cb(null, stream); }); ``` ```javascript // Variant 2: With options object zipfile.addReadStreamLazy("file.txt", { compress: true, compressionLevel: 9 }, function(cb) { var stream = fs.createReadStream("source.txt"); cb(null, stream); }); ``` ```javascript // Variant 3: With size for pre-calculation var fileSize = fs.statSync("data.bin").size; zipfile.addReadStreamLazy("data.bin", { size: fileSize, compress: false }, function(cb) { cb(null, fs.createReadStream("data.bin")); }); ``` ```javascript // Variant 4: Error handling in callback zipfile.addReadStreamLazy("optional.txt", function(cb) { fs.stat("optional.txt", function(err, stats) { if (err) { cb(err); // Error emitted from zipfile } else { cb(null, fs.createReadStream("optional.txt")); } }); }); ``` ```javascript // Variant 5: Multiple files with lazy loading var files = ["file1.txt", "file2.txt", "file3.txt"]; files.forEach(function(filename) { zipfile.addReadStreamLazy(filename, { compress: true, compressionLevel: 6 }, function(cb) { cb(null, fs.createReadStream(filename)); }); }); ``` -------------------------------- ### Constructor Signature Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Creates a new ZipFile instance with no parameters. Configuration is handled via method parameters or options objects. ```javascript var zipfile = new yazl.ZipFile(); ``` -------------------------------- ### Task: Serve ZIP from HTTP Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/README.md Example of creating a ZIP archive on the fly and serving it as an HTTP response using Express. ```javascript var express = require("express"); var yazl = require("yazl"); var app = express(); app.get("/download", function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(); res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", "attachment; filename=archive.zip"); zipfile.outputStream.pipe(res); }); ``` -------------------------------- ### HTTP Response with Error Handling Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/errors.md Example of handling errors when creating an HTTP response with a zip file. ```javascript var express = require("express"); var yazl = require("yazl"); var app = express(); app.get("/download", function(req, res) { var zipfile = new yazl.ZipFile(); zipfile.on("error", function(err) { console.error("Download failed:", err.message); if (!res.headersSent) { res.status(500).send("Failed to create archive"); } }); res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", "attachment; filename=archive.zip"); try { zipfile.addFile("file1.txt", "file1.txt"); zipfile.addFile("file2.txt", "file2.txt"); } catch (err) { console.error("Invalid file:", err.message); res.status(400).send("Invalid archive configuration"); return; } zipfile.end(function(totalSize) { if (totalSize !== -1) { res.setHeader("Content-Length", totalSize); } }); zipfile.outputStream.pipe(res); }); app.listen(3000); ``` -------------------------------- ### Timestamp Preservation Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/usage-examples.md Preserves the original modification times and file modes of files when adding them to the zip archive. ```javascript var fs = require("fs"); var yazl = require("yazl"); var zipfile = new yazl.ZipFile(); var files = ["old-file.txt", "recent-file.txt"]; files.forEach(function(file) { var stats = fs.statSync(file); zipfile.addFile(file, file, { mtime: stats.mtime, // Use actual file mtime mode: stats.mode, // Use actual file mode compress: true }); }); zipfile.end(); zipfile.outputStream.pipe(fs.createWriteStream("timestamps.zip")); ``` -------------------------------- ### File Comment Too Large Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/errors.md Example of triggering the 'fileComment is too large' error by exceeding the 65,535 byte limit. ```javascript try { var longComment = new Array(70000).join("x"); zipfile.addFile("file.txt", "file.txt", { fileComment: longComment // Error }); } catch (err) { console.error(err.message); // "fileComment is too large" } ``` -------------------------------- ### Invalid Call Sequences Source: https://github.com/thejoshwolfe/yazl/blob/master/_autodocs/api-reference/MethodSignatures.md Examples of incorrect usage of Yazl methods, leading to errors or unexpected behavior. ```javascript // ERROR: Adding after end() var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); zipfile.end(); zipfile.addFile("file2.txt", "file2.txt"); // THROWS // ERROR: Missing end() var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "file.txt"); // Output is never finalized // ERROR: Invalid path var zipfile = new yazl.ZipFile(); zipfile.addFile("file.txt", "/absolute/path.txt"); // THROWS // ERROR: Invalid options var zipfile = new yazl.ZipFile(); zipfile.addBuffer(data, "file.txt", {size: 100}); // THROWS (size not allowed) ```