In Node.js, you can create zip files using the built-in zlib
and fs
modules. Additionally, you can use external libraries like adm-zip
or archiver
to simplify the process.
Here’s an example using archiver
, a popular library for creating zip files
First, install archiver
via npm
npm install archiver
Then, here’s an example script to create a zip file using archiver
const fs = require('fs');
const archiver = require('archiver');
const output = fs.createWriteStream('example.zip');
const archive = archiver('zip', {
zlib: { level: 9 } // Compression level (optional)
});
output.on('close', () => {
console.log('Zip file created successfully');
});
archive.on('error', (err) => {
throw err;
});
archive.pipe(output);
// Add files or directories to the zip
archive.file('file1.txt', { name: 'file1.txt' });
archive.directory('images/', 'images'); // Add a directory and its contents
archive.finalize();
This script creates a zip file named example.zip
and adds file1.txt
and the contents of the images
directory to it. Customize the paths and file names as per your requirements.
Remember to handle errors appropriately, especially when dealing with file operations. Additionally, ensure you have the necessary permissions to write files to the specified directory.