Yoni Mayer Yoni Mayer - 3 years ago 109
Node.js Question

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

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.append("this is a test", { name: "test.txt"});


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

Answer Source

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() { 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download