Skip to main content

Mike Kreuzer

Download and unzip using Node

September 17, 2015

I unjustly maligned Node for not being able to unzip files properly. Or possibly I was right, and some combination of RVM, Ruby, Homebrew, NVM, Node or iojs and unzip weren't playing nicely together.

Update 24 September: turns out there are definite bugs in the Node unzip package. Spaces in files names, uncompressed archives, possibly other things & they fall over. Pity.

Update 29 September: The adm-zip module (so far!) has worked for me. As a bonus there's another module which uses adm-zip that already does what I was using as a test, downloading & unzipping Github repos: github-download

Node 4.0.0 is actually working pretty well, for the small number of hoops I'm asking it to jump through. Whatever was going on downloading and unzipping files is working now. So another Node code fragment, in case it's useful to anyone:

Update 15 September 2018: I removed the embedded gist that was here, the link hasn't changed.

Update November 2023: Here it is again, as I leave Github:

/*jslint node: true */
'use strict';

var fs = require('fs'),
    path = require('path'),

    fstream = require('fstream'),
    mkdirp = require('mkdirp'),
    request = require('request'),
    unzip = require('unzip');

function downloadAndUnzip(fromURL, toDir, zipFileName) {
    mkdirp(toDir, function (dirErr) {
        if (dirErr) {
            console.log(dirErr);
        } else {
            var zipFilePath = path.join(toDir, zipFileName);
            request(fromURL)
                .on('error', function (err) {
                    console.log(err);
                })
                .pipe(fs.createWriteStream(zipFilePath))
                .on('finish', function () {
                    var readStream = fs.createReadStream(zipFilePath),
                        writeStream = fstream.Writer(toDir);
                    readStream
                        .pipe(unzip.Parse())
                        .pipe(writeStream);
                });
        }
    });
}

// eg
downloadAndUnzip('https://github.com/mikekreuzer/Scipio/archive/0.2.1.zip',
                 'repoOwner',
                 'zipFileName.zip');