Calder
Calder

Reputation: 2308

Send zip created by node-zip

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?

Upvotes: 4

Views: 4117

Answers (2)

Calder
Calder

Reputation: 2308

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)

Upvotes: 6

bodokaiser
bodokaiser

Reputation: 15752

I recommend you to use streams for this approach.

var fs   = require('fs');
var zlib = require('zlib');
var http = require('http');

http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type': 'application/octet-stream' });   

    var readStream = fs.createReadStream('test.file');
    var unzipStream = zlib.createUnzip();    

    readStream.pipe(unzipStream.pipe(response));
}).listen(3000);

This will properly not work in real world (as I am not common with zlib) but it may give you the direction

Upvotes: 1

Related Questions