Send generated zip file using ExpressJS

I am using the express module on a NodeJS server to create a zip file. The express server responds to many requests, so I know that it is configured correctly, but I'm having problems creating a zip file and sending it back as a download.

I do not want to save the file, and then tell Express to send this file as a download, I just want to send the zip file as data from memory. Here is what I still have.

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 not one of them will decompress or decompress the ZIP archive, as if it had been corrupted. Any suggestions? Thank you in advance.

+4
source share
1 answer

You need to pass your parameters to zip.generate not zip.file . This creates a zip archive that I can correctly check / unzip through 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); }); 
+8
source

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


All Articles