Working with zip files in Node.js involves using third-party libraries as Node.js doesn't provide built-in support for zip file manipulation. One of the popular libraries for handling zip files in Node.js is adm-zip
. Below are the steps to work with zip files using adm-zip
:
-
Install
adm-zip:
You can install
adm-zip
using npm:npm install adm-zip
-
Extracting Files from a Zip Archive:
const AdmZip = require('adm-zip'); // Load a zip file const zip = new AdmZip('example.zip'); // Extract all files to the specified directory zip.extractAllTo(/* target path */, /* overwrite */ true);
-
Adding Files to a Zip Archive:
const AdmZip = require('adm-zip'); // Create a new zip file const zip = new AdmZip(); // Add a file zip.addFile(/* file name */, /* Buffer or content */, /* comment */); // Save the zip file zip.writeZip(/* target path */);
-
Reading Contents of a Zip Archive:
const AdmZip = require('adm-zip'); // Load a zip file const zip = new AdmZip('example.zip'); // Get an array of zip entries const zipEntries = zip.getEntries(); // Display the contents zipEntries.forEach(zipEntry => { console.log(zipEntry.entryName); });
-
Extracting a Specific File from a Zip Archive:
const AdmZip = require('adm-zip'); // Load a zip file const zip = new AdmZip('example.zip'); // Extract a specific file const zipEntry = zip.getEntry(/* file name */); if (zipEntry) { zip.extractEntryTo(zipEntry, /* target path */, /* maintainEntryPath */ true, /* overwrite */ true); }
Extracting all files from a zip archive:
const AdmZip = require('adm-zip'); const zip = new AdmZip('example.zip'); zip.extractAllTo('extracted_files', true);
Adding files to a zip archive:
const AdmZip = require('adm-zip'); const fs = require('fs'); const zip = new AdmZip(); const buffer = fs.readFileSync('file.txt'); zip.addFile('file.txt', buffer, 'This is a comment'); zip.writeZip('example.zip');
Reading contents of a zip archive:
const AdmZip = require('adm-zip'); const zip = new AdmZip('example.zip'); const zipEntries = zip.getEntries(); zipEntries.forEach(zipEntry => { console.log(zipEntry.entryName); });
With adm-zip
, you can easily manipulate zip files in Node.js, including extracting, adding, and reading files from zip archives.