Dynamically create and stream zip to client

后端 未结 4 1313
滥情空心
滥情空心 2020-12-02 11:36

I am using NodeJs (w/express) and I am trying to stream a zip file back to the client. The files contained in the zip do not live on the file system, rather they are create

4条回答
  •  醉话见心
    2020-12-02 12:02

    solution with: express.js, wait.for, zip-stream

    app.get('/api/box/:box/:key/download', function (req, res) {
    
        var wait = require('wait.for');
    
        var items = wait.for(function (next) {
            BoxItem.find({box: req.Box}).exec(next)
        });
    
        res.set('Content-Type', 'application/zip');
        res.set('Content-Disposition', 'attachment; filename=' + req.Box.id + '.zip');
    
        var ZipStream = require('zip-stream');
        var zip = new ZipStream();
    
        zip.on('error', function (err) {
            throw err;
        });
    
        zip.pipe(res);
    
        items.forEach(function (item) {
    
            wait.for(function (next) {
    
                var path = storage.getItemPath(req.Box, item);
                var source = require('fs').createReadStream(path);
    
                zip.entry(source, { name: item.name }, next);
            })
    
        });
    
        zip.finalize();
    
    });
    

提交回复
热议问题