Is it possible with Node.js streams to construct a zip archive and serve that zip archive to a client/user via a response to an HTTP GET request while it's being created? I'm searching for a solution that preferably avoids buffering the entire zip into memory on the server.
ZIP support in Node.js is at the moment a bit funky: the standard library supports zlib functionalities but they work on the file level (i.e. you can't create a ZIP archive that contains a full tree structure), some modules can only unzip data, some that can create ZIP files are ported from browser libraries and thus don't support stream.
Your best bet to compress a full directory is to use the zip binary using a child process, and pipe its output to the HTTP response:
var child = require('child_process');
var zipProcess = child.spawn('zip', ['-r', '-', 'directory_to_be_compressed']);
zipProcess.stdout.pipe(res);
However, if you only need to compress one file, you can use the zlib standard library:
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
inp.pipe(gzip).pipe(res);
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