I am using NodeJs (w/express) and I am trying to stream a zip file back to the client. The files contained in the zip do not live on the file system, rather they are create
solution with: express.js, wait.for, zip-stream
app.get('/api/box/:box/:key/download', function (req, res) {
var wait = require('wait.for');
var items = wait.for(function (next) {
BoxItem.find({box: req.Box}).exec(next)
});
res.set('Content-Type', 'application/zip');
res.set('Content-Disposition', 'attachment; filename=' + req.Box.id + '.zip');
var ZipStream = require('zip-stream');
var zip = new ZipStream();
zip.on('error', function (err) {
throw err;
});
zip.pipe(res);
items.forEach(function (item) {
wait.for(function (next) {
var path = storage.getItemPath(req.Box, item);
var source = require('fs').createReadStream(path);
zip.entry(source, { name: item.name }, next);
})
});
zip.finalize();
});