如何在nodejs中将多个文件转换为zip?

时间:2019-03-01 11:51:33

标签: node.js

这是我的代码:

因此有人帮助您将文件下载为zip文件夹

exports.downloadAllFiles = function(req,res){
    demodb.findOne({ guid: req.params.id }, function(err, data) { 
        if (err) {
            console.log("Error in finding case....");
            res.json(HttpStatus.INTERNAL_SERVER_ERROR, {});
        } else {
            if(data){
                // Here multiple files are contained in the data array
                //So I need to download the files into a zip folder
            }
        }
    })
    };

2 个答案:

答案 0 :(得分:1)

这是有关如何直接从本地目录和缓冲区添加文件的adm-zip的一个小示例:

// creating archives
var zip = new AdmZip();

// add file directly
zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here");
// add local file
zip.addLocalFile("/home/me/some_picture.png");
// get everything as a buffer
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");

在您的情况下,您可以在循环遍历数组的for循环中添加文件,并在每次递归中添加文件。

exports.downloadAllFiles = function(req,res){
demodb.findOne({ guid: req.params.id }, function(err, data) { 
    if (err) {
        console.log("Error in finding case....");
        res.json(HttpStatus.INTERNAL_SERVER_ERROR, {});
    } else {
        if(data){
            // for loop goes here:
            for(var i =0; i<data.length; i++){
              // add the files to zip
            }                
        }
    }
})
};

答案 1 :(得分:1)

您可以使用ADM-ZIP

    const zip=require('adm-zip');
    var zipper = new zip();
    zipper.addLocalFile('1.csv');
    zipper.addLocalFile('2.csv');
    zipper.addLocalFile('3.csv');
    zipper.writeZip("123.zip");