Node.js script to make a zip archive

While working in a node.js project, I had an use case where user will have to query based on days and query result will be pdf filtered by  the date range. And I have to create a directory of pdf files and return it as a zip file for the user.

As there are many modules related to zip, I tried couple of the active modules but none was meeting my requirements. And some of those modules has different bugs/issues which were open at that time. After different try/error and going through most of the zip modules, I used archiver.  And below a sample how it worked.

node_modules/*
*.data

view raw
.gitignore
hosted with ❤ by GitHub

npm install archiver;

view raw
install.sh
hosted with ❤ by GitHub

var archiver = require('archiver'),
archive = archiver('zip'),
fs = require('fs');
var output = fs.createWriteStream(__dirname + '/mocks.zip');
archive.pipe(output);
var getStream = function(fileName){
return fs.readFileSync(fileName);
}
//these are the files, want to put into zip archive
var fileNames = ['mock1.data', 'mock2.data', 'mock3.data'];
for(i=0; i<fileNames.length; i++){
var path = __dirname + '/'+fileNames[i];
archive.append(getStream(path), { name: fileNames[i]});
}
archive.finalize(function(err, bytes) {
if (err) {
throw err;
}
console.log(bytes + ' total bytes');
});

view raw
zipArchiver.js
hosted with ❤ by GitHub

 

After cloning the gist make sure you have files to zip and run the script like below:

node_archiver

Happy coding 🙂

One comment

  1. Gavin Glen · April 22, 2016

    Brilliant and worked first time.
    Coded exactly as above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.