Send generated zip file with ExpressJS
Asked Answered
C

1

11

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.

Celinacelinda answered 20/8, 2013 at 23:9 Comment(0)
R
12

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);
});
Rounder answered 21/8, 2013 at 0:36 Comment(3)
Can I do this without saving to hdd?Pungent
Yes, zip.generate gives you in-memory data. From there you can decide to stream it as an HTTP response body or wherever else you like.Rounder
Note 2018: node-zip seems not active anymore and is an extremely thin wrapper around JSZip. Just use JSZip directly, since it's more active.Gabler

© 2022 - 2024 — McMap. All rights reserved.