Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send zip created by node-zip

Tags:

node.js

jszip

Let's say you create a zip file in-memory following the example from node-zip's documentation:

var zip = new require('node-zip')()
zip.file('test.file', 'hello there')
var data = zip.generate({type:'string'})

How do you then send data to a browser such that it will accept it as a download?

I tried this, but the download hangs at 150/150 bytes AND makes Chrome start eating 100% CPU:

res.setHeader('Content-type: application/zip')
res.setHeader('Content-disposition', 'attachment; filename=Zippy.zip');
res.send(data)

So what's the proper way to send zip data to a browser?

like image 782
Calder Avatar asked Sep 02 '25 06:09

Calder


1 Answers

Using the archiver and string-stream packages:

var archiver = require('archiver')
var fs = require('fs')
var StringStream = require('string-stream')

http.createServer(function(request, response) {
  var dl = archiver('zip')
  dl.pipe(response)
  dl.append(new fs.createReadStream('/path/to/some/file.txt'), {name:'YoDog/SubFolder/static.txt'})
  dl.append(new StringStream("Ooh dynamic stuff!"), {name:'YoDog/dynamic.txt'})
  dl.finalize(function (err) {
    if (err) res.send(500)
  })
}).listen(3000)
like image 144
Calder Avatar answered Sep 04 '25 20:09

Calder