JSZip处于循环中吗?

时间:2018-11-04 22:29:44

标签: javascript node.js loops jszip nodejs-jszip

是否可以使用JSZip循环创建真正的zip文件夹和文件,每个元素一个?如果可以,怎么办?

类似这样的东西:

var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

for(i = 0; i > 5; i++){
    var zip = new JSZip();
    zip.folder(i).file(i+".txt", i);

    zip
    .generateNodeStream({type:'nodebuffer',streamFiles:true})
    .pipe(fs.createWriteStream('Zipped Projects.zip'))
    .on('finish', function () {
        console.log("Zipped Projects.zip written.");
    })
}

在循环之外,将创建一个实际的zip文件夹,并在当前目录中包含预期的内容。在循环内部,什么都没有发生,甚至日志也没有。

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则说明此问题是由每次循环迭代创建新的zip对象引起的。

也许您可以考虑进行以下调整以解决此问题:

var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

// Create the single zip object that will be populated
// during the for loop
var zip = new JSZip();

// Populate the zip object with text files per iteration.
// Make sure you update the loop logic to use "i < 5"
for(var i = 0; i < 5; i++){
    zip.folder(i).file(i+".txt", i);
}

// Now that the zip object has been populated, write it to
// disk
zip
.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream('Zipped Projects.zip'))
.on('finish', function () {
    console.log("Zipped Projects.zip written.");
})

希望这会有所帮助!

答案 1 :(得分:0)

var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

var asanaProjects = require("C:/Users/GabrielRivera/Documents/asana/New Projects JSON.json");

async function createProjectZips() {

    var zip = new JSZip();

    asanaProjects.map((project, index, array) => {

        zip.file(project.name+' - '+index+'.json', JSON.stringify(project));        
    })

    zip
        .generateNodeStream({type:'nodebuffer',streamFiles:true})
        .pipe(fs.createWriteStream('Zipped Projects.zip'))
        .on('finish', function () {
        //console.log("Zipped Projects.zip written.");
        })
}

createProjectZips()
.then(() => {
})
.catch(err=>console.log(err))