Create ZIP file in memory using any node module
Asked Answered
S

2

7

Is there any node module to create zip in memory?(I don't want to save zip file on disk) so that we can send this created zip file to other server(From memory). What is the best way to do this? Here is my example:

var file_system = require('fs');
var archiver = require('archiver');
var dirToCompress = 'directoryToZIP';

module.exports = function (req, res, next) {
var archive = archiver.create('zip', {});
archive.on('error', function (err) {
    throw err;
});

    var output = file_system.createWriteStream('/testDir/myZip.zip',{flags:'a'});//I don't want this line
    output.on('close', function () {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    archive.pipe(output);

    archive.directory(dirToCompress);

    archive.finalize();

};
Suh answered 24/3, 2017 at 6:13 Comment(2)
I suggest using archiver and pipe the stream to response, this way you will not have to write anything to disk.Mors
Here Output variable will be api of other server so that we can send this zip file.Suh
S
9

I'm using Adm-Zip:

// create archive
var zip = new AdmZip();

// add in-memory file
var content = "inner content of the file";
zip.addFile("test.txt", Buffer.alloc(content.length, content), "entry comment goes here");

// add file
zip.addLocalFile("/home/me/some_picture.png");

// get in-memory zip
var willSendthis = zip.toBuffer();

Schuss answered 7/2, 2020 at 13:28 Comment(0)
N
3

If GZip will do, you can use the built-in zlib module and not even have to load an external module.

const gzip = zlib.createGzip();

// If you have an inputStream and an outputStream:

inputStream.pipe(gzip).pipe(outputStream);

For Zip and not GZip, you can check out archiver or zip-stream.

Nimbus answered 24/3, 2017 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.