Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert multiple files to compressed zip file using node js

Tags:

node.js

zip

I want to convert multiple files to a compressed zip file on node.js.

I tried the following code:

var archiver = require('archiver');
var fs = require('fs');
var StringStream = require('string-stream');

http.createServer(function(request, response) {
    var dl = archiver('data');
    dl.pipe(response);
    dl.append(new fs.createReadStream('test/fixtures/test.txt'), {
        name: 'stream.txt', date: testDate2
    });
    dl.append(new StringStream("Ooh dynamic stuff!"), {
        name : 'YoDog/dynamic.txt'
    });
    dl.finalize(function(err) {
        if (err)
            res.send(200000)
    });
}).listen(3500);
like image 672
Kusuma Jammula Avatar asked Aug 09 '13 07:08

Kusuma Jammula


People also ask

How do I compress multiple files into a ZIP file?

Right-click on the file or folder. Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I zip all files individually?

Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.


1 Answers

There is a much simpler solution with the archiver module:

var fs = require('fs');
var archiver = require('archiver');
var output = fs.createWriteStream('./example.zip');
var archive = archiver('zip', {
    gzip: true,
    zlib: { level: 9 } // Sets the compression level.
});

archive.on('error', function(err) {
  throw err;
});

// pipe archive data to the output file
archive.pipe(output);

// append files
archive.file('/path/to/file0.txt', {name: 'file0-or-change-this-whatever.txt'});
archive.file('/path/to/README.md', {name: 'foobar.md'});

//
archive.finalize();

It also supports tar archives, just replace 'zip' by 'tar' at line 4.

I get no credit for this code, it's just part of the README (you should check it out for other means of adding stuff into the archive).

Neat package, and it's probably the only one that's still being maintained and documented properly.

like image 55
Overdrivr Avatar answered Sep 23 '22 16:09

Overdrivr