How to zip an entire directory using Node.js?

Sometimes, we want to zip an entire directory using Node.js.

In this article, we’ll look at how to zip an entire directory using Node.js.

How to zip an entire directory using Node.js?

To zip an entire directory using Node.js, we can use the archiver package.

We install the package by running

npm i archiver

Then we write

const fs = require('fs');
const archiver = require('archiver');

const output = fs.createWriteStream('target.zip');
const archive = archiver('zip');

output.on('close', () => {
  console.log(archive.pointer() + ' total bytes');
});

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

archive.pipe(output);
archive.directory(sourceDir, false);
archive.directory('subdir/', 'new-subdir');

archive.finalize();

to call fs.createWriteStream with the path to the zip file.

And then we call archiver with 'zip' to create a zip file.

We call archive.pipe with output to pipe the content directory content to the zip file.

Then we call archive.directory with the directories we want to put in the zip file.

We call output.on with 'close' to run the callback when the write stream is done.

And we call archive.on with 'error' to listen for errors when making the zip file.

Finally, we call archive.finalize to finish the archiving operation.

Conclusion

To zip an entire directory using Node.js, we can use the archiver package.