Node.js zip compression to memory

I want to pin some data into a writeableStream.

The goal is to do everything in memory, and not create the actual zip file on disk.

For testing purposes only, I create a ZIP file on disk. But when I try to open output.zip , I get the following error: "the archive is in an unknown format or is corrupt." (WinZip on Windows 7, as well as a similar MAC error)

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!'); }); 
+5
source share
1 answer

You do not expect the contents to be written to the output stream.

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

Source: https://habr.com/ru/post/1270070/


All Articles