Node.js Archiving Essentials: Zip and Unzip Demystified
Step-by-Step Guide to Zipping and Unzipping Files in Node.js
File compression plays a pivotal role in optimizing data storage and transfer. By reducing the size of files and folders, we not only save space but also expedite the process of sharing and downloading. In the realm of Node.js, the capability to zip and unzip files is a valuable asset for developers seeking efficiency in file handling.
The Blog is divided into 3 sections:
- Zipping
- Unzipping
- Code Execution
Zipping: The Compression Process
In this section, we will explore the following topics:
- Installation
- Zipping Single File
- Zipping Multiple Files
- Zipping a Folder
- Updating a Zip
Installing JSZip
To perform zipping operations in Node.js, we can utilize the jszip package. This package provides comprehensive functionalities for creating and managing ZIP archives.
Before diving into zipping operations, ensure you have installed the jszip package using the following command:
npm i jszip
Zipping Single File
Zipping a single file involves creating a ZIP archive and adding the file to it. Here’s an example of how to zip a file named ‘myfile.txt’ that is situated in the same directory as index.js:
// index.js
const JSZip = require("jszip");
const fs = require("fs");
const path = require("path");
const compressSingleFile = (filePath, zipName) => {
const zip = new JSZip();
const fileContent = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
zip.file(fileName, fileContent);
const zipFileName = `${zipName}.zip`;
zip
.generateAsync({ type: "nodebuffer" })
.then((content) => {
fs.writeFileSync(zipFileName, content);
})
.catch((error) => console.log(error));
console.log(`Zip file created: ${zipFileName}`);
};
// Usage:
compressSingleFile("./myfile.txt", "myfile-compressed");
// File path can be just "myfile.txt", as it shares the same parent with the index.js
Zipping Multiple Files
Zipping multiple files follows a similar approach. Simply add each file to the ZIP archive using the zip.file()
method:
// index.js
const JSZip = require("jszip");
const fs = require("fs");
const path = require("path");
const compressMultipleFiles = (zipName, ...files) => {
const zip = new JSZip();
const addFileToZip = (zipFile, filePath) => {
const fileContent = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
zipFile.file(fileName, fileContent);
};
for (const file of files) {
addFileToZip(zip, file);
}
const zipFileName = `${zipName}.zip`;
zip.generateAsync({ type: "nodebuffer" }).then((content) => {
fs.writeFileSync(zipFileName, content);
}).catch((error) => console.log(error));;
console.log(`Zip file created: ${zipFileName}`);
};
// Usage:
const zipName = "files-compressed";
const filesToBeCompressed = ["./myfile.txt", "picture1.jpeg", "bg.mp4"];
compressMultipleFiles(zipName, ...filesToBeCompressed);
Zipping a Folder: A Comprehensive Approach
Zipping a folder involves creating a ZIP archive that consolidates all files, folders, subfolders, and nested files within.
This comprehensive approach ensures that the entire directory structure is maintained during compression. Here’s an example of how to zip a folder named ‘myFolder’:
// index.js
const JSZip = require("jszip");
const fs = require("fs");
const path = require("path");
const zipFolder = (folderPath, zipFilePath) => {
const zip = new JSZip();
const addFilesToZip = (zipFile, folderPath, currentPath = "") => {
const files = fs.readdirSync(path.join(folderPath, currentPath));
for (const file of files) {
const filePath = path.join(currentPath, file);
const fullFilePath = path.join(folderPath, filePath);
const stats = fs.statSync(fullFilePath);
if (stats.isDirectory()) {
addFilesToZip(zipFile, folderPath, filePath);
} else {
fileContent = fs.readFileSync(fullFilePath);
zipFile.file(filePath, fileContent);
}
}
};
addFilesToZip(zip, folderPath);
zip.generateAsync({ type: "nodebuffer" }).then((content) => {
fs.writeFileSync(zipFilePath, content);
}).catch((error) => console.log(error));;
console.log(`Zip file created at: ${zipFilePath}`);
};
// Usage:
const folder = "./myFolder";
const zipName = "./myFolder-compressed.zip";
zipFolder(folder, zipName);
Updating a Zip: Dynamic Modifications
Adding new files to an existing ZIP archive is straightforward. Simply create a JSZip instance and open the existing ZIP file. Then, add the new files using the zip.file()
method:
A crucial note is that if a file already exists in the zip, pushing a new file with the same name replaces the existing one.
// index.js
const JSZip = require("jszip");
const fs = require("fs");
const path = require("path");
const updateZipFile = (existingZipPath, ...files) => {
// Read the existing ZIP file
const existingZipData = fs.readFileSync(existingZipPath);
const zip = new JSZip();
zip.loadAsync(existingZipData).then((zip) => {
// Add new files to the ZIP
const addFileToZip = (zipFile, filePath) => {
const fileContent = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
zipFile.file(fileName, fileContent);
};
for (const file of files) {
addFileToZip(zip, file);
}
// Generate the updated ZIP file
zip
.generateAsync({ type: "nodebuffer" })
.then((updatedZipData) => {
fs.writeFileSync(existingZipPath, updatedZipData);
console.log("Updated ZIP file created successfully.");
})
.catch((error) => console.log(error));
});
};
// Usage:
updateZipFile("archives.zip", "./song1.mp3", "photo-copy.jpeg");
Unzipping: Unleashing the Packed Contents
Unzipping files is as easy as installing the ‘decompress’ package. The following code snippet demonstrates the simplicity of the process:
Install it using npm:
npm i decompress
Here’s an example on how to unzip a zip file named ‘archives.zip’:
Make sure the zip file is located in the same directory as ‘index.js’
// index.js
const Decompress = require("decompress");
Decompress("myfile-compressed.zip", "archives-unzipped")
.then((files) => {
console.log("Done Unzipping!");
})
.catch((error) => console.log(error));
Executing the Code: Unleashing the Power of Node.js
Now that we’ve delved into the intricacies of zipping and unzipping files, let’s put our knowledge to the test by executing the code.
To run the code examples seamlessly, open your terminal, navigate to the directory where your script (index.js) is located, and execute the following command:
node index.js
Conclusion
In this guide, we’ve demystified the process of zipping and unzipping files in Node.js. By harnessing the power of ‘JSZIP’ for zipping and ‘decompress’ for unzipping, developers can streamline file operations, enhance efficiency, and optimize data handling. Whether you’re compressing single files, multiple files, or entire folders, Node.js provides the essential tools to simplify the archiving process. Explore further, experiment, and unlock the full potential of file compression in your Node.js projects.
Thank you all for taking the time to read my blog post!
I invite you to share your own asynchronous versions of the code or any modifications you find interesting. Drop your comments below — I’m excited to see your take on it!
Happy coding! 💻💬