假设您按照node-zip
文档中的示例在内存中创建了一个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数据发送到浏览器的正确方法是什么?
答案 0 :(得分:6)
使用archiver和string-stream套餐:
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)
答案 1 :(得分: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),但它可能会给你方向