Introduction to Archiver
The archiver module is a powerful tool to create archives, such as zip and tar files, in Node.js. It is an essential package for Node.js developers who want to manipulate and manage archives efficiently. This guide dives into the usage of archiver and provides numerous API examples to help you get the most out of this robust module.
Installation
npm install archiver
Basic Usage
const fs = require('fs');
const archiver = require('archiver');
const output = fs.createWriteStream(__dirname + '/example.zip');
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', function() {
console.log(`Archive created: ${archive.pointer()} total bytes`);
});
archive.pipe(output);
archive.append(fs.createReadStream('file1.txt'), { name: 'file1.txt' });
archive.append(fs.createReadStream('file2.txt'), { name: 'file2.txt' });
archive.finalize();
Appending Files and Directories
Appending files and directories is straightforward using the archiver
API. Below are a few different ways to append content:
Append a File
const filePath = 'file.txt';
archive.append(fs.createReadStream(filePath), { name: 'file.txt' });
Append a Directory
const directoryPath = 'mydir';
archive.directory(directoryPath, false);
Advanced Example: Complete Web App File Archiving
const express = require('express');
const fs = require('fs');
const archiver = require('archiver');
const app = express();
app.get('/download', function(req, res) {
const output = fs.createWriteStream(__dirname + '/staticArchive.zip');
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', function() {
console.log(`Archive created with ${archive.pointer()} total bytes`);
res.download(__dirname + '/staticArchive.zip');
});
archive.pipe(output);
archive.directory(__dirname + '/public/', false);
archive.finalize();
});
app.listen(3000, function() {
console.log('App listening on port 3000');
});
This complete web app allows users to download a zipped archive of the public
directory when they navigate to the /download
endpoint. The code utilizes express to handle requests and archiver to create the zip file.
With the extensive examples provided in this guide, you can now efficiently manage and manipulate file archives in your Node.js applications using the archiver module. Happy archiving!
Hash: 539d1b2d6fe0b8f8149afd750aee63b19bf1bae1e6b21538a30d50bf073c8dee