假设您按照node-zip文档中的示例在内存中创建了一个zip文件: var zip = new require('node-zip')()zip.file('test.file', 'hello there')var data = zip.generate({type:'string'}) 那么你如何将数据发送到浏览器,以便
var zip = new require('node-zip')() zip.file('test.file', 'hello there') var data = zip.generate({type:'string'})
那么你如何将数据发送到浏览器,以便它接受下载?
我尝试了这个,但下载挂起150/150字节并使Chrome开始吃掉100%的CPU:
res.setHeader('Content-type: application/zip') res.setHeader('Content-disposition', 'attachment; filename=Zippy.zip'); res.send(data)
那么将zip数据发送到浏览器的正确方法是什么?
使用 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)