Zip Files in a Node.js Using Archiver
In this article, we'll look at a simple way to zip files in a Node.js application using a library called archiver
.
This tool makes it easy to create zip files programmatically, which can be useful for various tasks such as archiving logs, preparing files for download, or packaging assets.
Before coding, you'll need to install the archiver
library:
npm install archiver
Once the library is installed, you can write a Node.js script to zip files.
Create a Function to Zip Files
Create a function that takes the path where the zip file will be saved and a list of files to zip:
const fs = require("fs"); const archiver = require("archiver"); function zipFiles(outputPath, files) { const output = fs.createWriteStream(outputPath); const archive = archiver("zip", { zlib: { level: 9 } }); output.on("close", function () { console.log( "Archive created successfully. Total bytes: " + archive.pointer() ); }); archive.on("error", function (err) { throw err; }); archive.pipe(output); files.forEach((file) => { archive.file(file, { name: file.split("/").pop() }); }); archive.finalize(); }
- The code begins by setting up the file stream and the archiver.
- It listens for the 'close' event to log when the archive is complete and an 'error' event to handle potential errors.
- The script adds files to the archive using the
file
method and usesfinalize
to finish the archiving process.
Now, here’s how you can use the function:
const filesToZip = ['path/to/file1.txt', 'path/to/file2.txt']; zipFiles('output.zip', filesToZip);
This script zips the specified files into an archive named output.zip
. Once you build the function, you can use it wherever you need it.
A handy one to have in your own library for later.