Zipped files take up half the storage space that uncompressed files take, and one can quickly transfer the zipped file through email and other means. The recipient can unzip the file and view the contents in their original formats.
To zip files using a node command, one needs to install the archiver
dependency. Since the archiver
is an npm
module, we can install it by running the following command in the terminal:
npm install archiver --save
We can zip multiple files using node modules by following the steps given below:
To use the Node modules, we need to require them at the program’s start. The require
method uses the source code of the archiver from the node_modules directory. Hence, this will be the first step.
We will then create a file to write the stream. Streams convert massive operations into smaller manageable chunks. We will set up the archiver.
We declare it a zip file using the zlip
data compression method. We set the compression level to 9. Give names to the directory and the compressed zip file. In the code below, they are _dirname
and example
, respectively.
When the file stream has closed, we will run a callback that will inform the programmer that the function has written all archive data. We include another callback for error handling (warnings like stat failures and non-blocking errors might occur as well).
We will then pipe the archive data to the archiver and append the files we want to add to the zip file.
Once we have appended the files, we will finalize the archive as the last step.
The steps mentioned above are given in the code below:
//Step 1 - require modulesconst fs = require('fs');const archiver = require('archiver');//Step 2 - create a file to stream archive data toconst output = fs.createWriteStream(__dirname + '/example.zip');const archive = archiver('zip', {zlib: { level: 9 }});//Step 3 - callbacksoutput.on('close', () => {console.log('Archive finished.');});archive.on('error', (err) => {throw err;});//Step 4 - pipe and append filesarchive.pipe(output);const text1 = path.join(__dirname, 'file1.txt');const text2 = path.join(__dirname, 'file2.txt');archive.append(fs.createReadStream(text1), { name: 'newfile1.txt' });archive.append(fs.createReadStream(text2), { name: 'newfile2.txt' });//Step 5 - finalizearchive.finalize();
Free Resources