I'm using the express module in a NodeJS server to generate a zip file. The express server is responding to many requests, so I know that is set up correctly, but I'm having trouble generating a zip file and sending that back as a downloadable.
I don't want to save the file and then tell Express to send that file as a download, I just want to send the zip file as data from memory. Here is what I have so far.
function buildZipFile(data, filename) {
var zip = new require('node-zip')();
zip.file(filename, data, { base64: false });
return zip.generate();
}
var data = buildZipFile('hello world', 'hello.txt');
res.set('Content-Type', 'application/zip')
res.set('Content-Disposition', 'attachment; filename=file.zip');
res.set('Content-Length', data.length);
res.end(data, 'binary');
return;
The file will return, but neither windows unzip or 7zip are able to open the archive, as if it is corrupt. Any suggestions? Thank you in advance.
You need to pass your options to zip.generate
not zip.file
. This creates a zip archive I can properly inspect/unzip via zipinfo
/unzip
.
var fs = require('fs');
var Zip = require('node-zip');
var zip = new Zip;
zip.file('hello.txt', 'Hello, World!');
var options = {base64: false, compression:'DEFLATE'};
fs.writeFile('test1.zip', zip.generate(options), 'binary', function (error) {
console.log('wrote test1.zip', error);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With