Download and Unzip a Zip file with Node.js

1. Install a javascript zip implementation. I like adm-zip.

npm install adm-zip

2. Require the node http module

var http = require('http')

3. Require the node file system module (fs)

var fs = require('fs')

5. Construct your temporary file path

var tmpFilePath = "assets/tmp/" + filename + ".zip"

6. Use http to get the url to the zip file, then synchronously append the data to the temporary file path. Use AdmZip to extract the zip to another directory.

7. Delete the zip file

Code and usage:

		var download = function(filename, url) {
			var tmpFilePath = "assets/tmp/" + filename + ".zip"
			http.get(url, function(response) {
		 		response.on('data', function (data) {
		 			fs.appendFileSync(tmpFilePath, data)
				});
		 		response.on('end', function() {
		 			 var zip = new AdmZip(tmpFilePath)
		 			 zip.extractAllTo("assets/extracted/" + filename)
		 			 fs.unlink(tmpFilePath)
			 	})
		 	});
		}

		for (var i = 0; i < objectsToDownload.length; i++) {
			download(objectsToDownload[i].filename, objectsToDownload[i].url)
		 }

1 thought on “Download and Unzip a Zip file with Node.js”

Leave a Reply

Your email address will not be published. Required fields are marked *