Yoni Mayer
Yoni Mayer

Reputation: 1238

node.js compressing ZIP to memory

I want to zip some data into a writableStream.

the purpose is to do all in memory and not to create an actual zip file on disk.

For testing only, i'm creating a ZIP file on disk. But when I try to open output.zip i get the following error: "the archive is either in unknown format or damaged". (WinZip at Windows 7 and also a similar error on MAC)

What am I doing wrong?

const   fs = require('fs'),
    archiver = require('archiver'),
    streamBuffers = require('stream-buffers');

let outputStreamBuffer = new streamBuffers.WritableStreamBuffer({
    initialSize: (1000 * 1024),   // start at 1000 kilobytes.
    incrementAmount: (1000 * 1024) // grow by 1000 kilobytes each time buffer overflows.
});

let archive = archiver('zip', {
    zlib: { level: 9 } // Sets the compression level.
});
archive.pipe(outputStreamBuffer);

archive.append("this is a test", { name: "test.txt"});
archive.finalize();

outputStreamBuffer.end();

fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() { console.log('done!'); });

Upvotes: 7

Views: 2745

Answers (1)

Mahesh J
Mahesh J

Reputation: 520

You are not waiting for the content to be written to the output stream.

Comment out outputStreamBuffer.end(); from your code and change it to the following...

outputStreamBuffer.on('finish', function () {
    fs.writeFile('output.zip', outputStreamBuffer.getContents(), function() { 
        console.log('done!');
    });
});

Upvotes: 6

Related Questions