Kusuma Jammula
Kusuma Jammula

Reputation: 121

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

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);

Upvotes: 12

Views: 32855

Answers (3)

Overdrivr
Overdrivr

Reputation: 6606

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'});

// wait for streams to complete
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.

Upvotes: 26

Maghalakshmi Saravana
Maghalakshmi Saravana

Reputation: 811

To Compress the text file using node js

var fs=require('fs');
var Zlib=require('zlib');
fs.createReadStream('input.txt').pipe(Zlib.createGzip()).pipe(fs.createWriteStream('input.txt.gz'));

Upvotes: -3

WaughWaugh
WaughWaugh

Reputation: 1032

For zipping up multiple files, you can use this utility method I wrote with the archiver module:-

var zipLogs = function(working_directory) {
    var fs = require('fs');
    var path = require('path');
    var output = fs.createWriteStream(path.join(working_directory, 'logs.zip'));
    var archiver =  require('archiver');
    var zipArchive = archiver('zip');

    zipArchive.pipe(output);
    zipArchive.bulk([{src: [path.join(working_directory, '*.log')],  expand: true}]);
    zipArchive.finalize(function(err, bytes) {
        if (err)
            throw err;

    console.log('done:', base, bytes);
    });
}

This for example, zips up all the log files in a particular directory.

Upvotes: 4

Related Questions