Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to zip together files with a simple node command

Umme Ammara

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:

  1. 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.

  2. 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.

  3. 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).

  4. We will then pipe the archive data to the archiver and append the files we want to add to the zip file.

  5. 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 modules
const fs = require('fs');
const archiver = require('archiver');

//Step 2 - create a file to stream archive data to
const output = fs.createWriteStream(__dirname + '/');
const archive = archiver('zip', {
  zlib: { level: 9 } 

//Step 3 - callbacks 
output.on('close', () => {
  console.log('Archive finished.');

archive.on('error', (err) => {
  throw err;

//Step 4 - pipe and append files
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 - finalize




Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring