Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Creating a zip archive from a folder and preserving structure with Node.js

Creating a zip archive from a folder and preserving structure with Node.js

Problem

I'm trying to use Node.js to create a zip file from an existing folder, and preserve the structure.

I was hoping there would be a simple module to allow this kind of thing:

archiver.create("../folder", function(zipFile){ 
    console.log('et viola');
});

but I can't find anything of the sort!

I've been googling around, and the best I've found so far is zipstream, but as far as I can tell there's no way to do what I want. I don't really want to call into commandline utilities, as the the app has to be cross platform.

Any help would be greatly appreciated.

Thanks.

Problem courtesy of: user1257359

Solution

It's not entirely code free, but you can use node-native-zip in conjunction with folder.js. Usage:

function zipUpAFolder (dir, callback) {
    var archive = new zip();

    // map all files in the approot thru this function
    folder.mapAllFiles(dir, function (path, stats, callback) {
        // prepare for the .addFiles function
        callback({ 
            name: path.replace(dir, "").substr(1), 
            path: path 
        });
    }, function (err, data) {
        if (err) return callback(err);

        // add the files to the zip
        archive.addFiles(data, function (err) {
            if (err) return callback(err);

            // write the zip file
            fs.writeFile(dir + ".zip", archive.toBuffer(), function (err) {
                if (err) return callback(err);

                callback(null, dir + ".zip");
            });                    
        });
    });    
}
Solution courtesy of: Jan Jongboom

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Creating a zip archive from a folder and preserving structure with Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×