Casey Flynn
Casey Flynn

Reputation: 14048

Node.js stream into zip archive and stream zip archive as response to client

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.

Upvotes: 5

Views: 6585

Answers (2)

scosman
scosman

Reputation: 2593

It's not Node, but this project does exactly what you're looking for. You can host it as a standalone server and call it from Node:

https://github.com/scosman/zipstreamer

Upvotes: -2

Paul Mougel
Paul Mougel

Reputation: 17048

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);

Upvotes: 1

Related Questions