3

假设您按照文档中的示例在内存中创建了一个 zip 文件node-zip

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

然后,您如何将其发送data到浏览器以使其接受下载?

我试过这个,但下载挂起在 150/150 字节并且使 Chrome 开始消耗 100% CPU:

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

那么将 zip 数据发送到浏览器的正确方法是什么?

4

2 回答 2

6

使用归档器字符串流包:

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)
于 2013-07-13T19:26:53.130 回答
1

我建议您为此方法使用流。

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

这在现实世界中是行不通的(因为我不喜欢 zlib),但它可能会给你指明方向

于 2013-07-13T08:25:50.710 回答