Node.js jszip库的文件提取功能

6

我正在编写一些Node.js代码,使用jszip来压缩和解压缩一些文件。我知道如何进行压缩,但无法弄清如何解压缩或解压缩。在stackoverflow上有几个链接不起作用。有人有什么解决方案吗? 以下是我尝试过的内容

var fs = require('fs');
var JSZip   = require('jszip');
var zipName = "C:/test.zip";
var unzip = "C:/unzip";


fs.readFile(zipName, function (err, data) {
    if (err) throw err;
    var zip = new JSZip();
    zip.folder(unzip).load(data);
});
2个回答

9

JSZip没有将文件写入磁盘的方法。要实现它,您需要遍历 zip.files

var path = require("path");
Object.keys(zip.files).forEach(function(filename) {
  var content = zip.files[filename].asNodeBuffer();
  var dest = path.join(unzip, filename);
  fs.writeFileSync(dest, content);
}

在一个zip文件中,使用斜杠'/'表示文件夹,我认为path.join()可以创建正确的路径,但我无法测试。


你好,先生。看起来你忘记了一个右括号。 - Josh Stovall

0

可能是由于我错误地实现了asNodeBuffer并且对JS缺乏经验,但我一直在错误地提取文件。 我想分享对我有效的方法,我已经使用250+ MB的文件进行了测试。

...
fs.readFile(tmpFilePath, function (err, data) {
    if (err) {
        throw err;
    }
    logger.debug('[method] Before extracting file...');
    JSZip.loadAsync(data).then(function (zip) {
        var files = Object.keys(zip.files);
        logger.debug('[method] files to be created ' + files.length);
        // in my case, the folders where not being created while "inflating" the content. created the folders in a separated loop 
        // O(n) for those geeks on complexity. 
        createDirectories(files);
        createFiles(files, zip, someOtherFunctionReference);
    }).catch(function (err) {
        deferred.reject(err);
    });
});
...

/**
 * Sync opperation to create the folders required for the files.
 * @param files
 */
function createDirectories(files) {
    files.forEach(function (filename) {
        var dest = path.join(folderName, filename);
        ensureDirectoryExistence(dest);
    });
}

/**
 * recursive create directory function
 * @param filePath
 * @returns {boolean}
 */
function ensureDirectoryExistence(filePath) {
    var dirname = path.dirname(filePath);
    if (fs.existsSync(dirname)) {
        return true;
    }
    ensureDirectoryExistence(dirname);
    fs.mkdirSync(dirname);
}

/**
 * Create files sync or blocking
 * @param files
 * @param zip
 * @param cb
 */
function createFiles(files, zip, cb) {
    try {
        var countFilesCreated = 0;
        files.forEach(function (filename) {
            var dest = path.join(folderName, filename);
            // skip directories listed
            if (dest.charAt(dest.length - 1) === '/') {
                countFilesCreated++;
                return;
            }
            return zip.file(filename).async('nodebuffer').then(function(content){
                // var content = zip.files[filename].nodeStream();
                fs.writeFileSync(dest, content);
                countFilesCreated++;
                // proably someone with more experience in JS can implement a promice like solution. 
                // I thought that in here instead of the counter we coud use an indexOf to return an error in case not all the elements where created correctly. 
                // but if a file throw an error, its handled by the catch ... 
                if (countFilesCreated >= files.length) {
                    logger.debug('All files created!!');
                    cb();
                }
            });
        });
    } catch (err) {
        throw err;
    }
}

希望这能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接