Monday, July 31, 2017

node.js compressing ZIP to memory

Leave a Comment

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

1 Answers

Answers 1

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!');     }); }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment