Handling Zip files in NodeJS applications.


Often it happens you might need to deploy, download or update resources for your application in runtime. For one such scenario, there is this quick way that will come handy.

process

Ideally, this would be the flow that we’ll follow.

To perform the ZIP operations we shall be consuming adm-zip which is available as npm package.

Installing adm-zip:

$ npm install adm-zip

Code:

var file_url = 'https://downloadurl.com/files/my_zip_file.zip';
var AdmZip = require('adm-zip'); //Reference: https://www.npmjs.com/package/adm-zip
var https = require('https');
var fs = require('fs')
https.get(file_url, function (res) {
var data = [], dataLen = 0;
res.on('data', function (chunk) {
data.push(chunk);
dataLen += chunk.length;
}).on('end', function () {
var buf = Buffer.alloc(dataLen);
for (var i = 0, len = data.length, pos = 0; i < len; i++) {
data[i].copy(buf, pos);
pos += data[i].length;
}
var zip = new AdmZip(buf);
var dir = './relative_path/zip_test/';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
zip.extractAllTo(/*target path*/dir, /*overwrite*/true);
});
});
view raw zip-nodejs.js hosted with ❤ by GitHub
File Download URL: var file_url = 'https://downloadurl.com/files/my_zip_file.zip';

Download URL for the file can be dynamically handled and using http.get we will get the file from the host location. Once we have the file we read the data as a byte stream and write its content to buffer. Using that buffer with adm-zip we then unzip the file to a location desired, this could be an absolute or relative location as per requirement.

Certainly, this is just one thing that can be done using adm-zip you may explore more options available, like selectively unzipping, or updating an existing file system and overrides, etc. Here!

That shall be all.

Pingback for assistance, your Feedback’s are always a welcome… 🙂

Regards,
Aditya Deshpande

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