【问题标题】:Creating a zip archive from a folder and preserving structure with Node.js从文件夹创建 zip 存档并使用 Node.js 保留结构
【发布时间】:2012-03-23 15:15:32
【问题描述】:

我正在尝试使用 Node.js 从现有文件夹创建一个 zip 文件,并保留结构。

我希望有一个简单的模块来允许这种事情:

archiver.create("../folder", function(zipFile){ 
    console.log('et viola');
});

但我找不到类似的东西!

我一直在谷歌搜索,到目前为止我发现最好的是 zipstream,但据我所知,没有办法做我想做的事。我真的不想调用命令行实用程序,因为应用程序必须是跨平台的。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: javascript node.js zipstream


    【解决方案1】:

    它并非完全免费,但您可以将node-native-zipfolder.js 结合使用。用法:

    function zipUpAFolder (dir, callback) {
        var archive = new zip();
    
        // map all files in the approot thru this function
        folder.mapAllFiles(dir, function (path, stats, callback) {
            // prepare for the .addFiles function
            callback({ 
                name: path.replace(dir, "").substr(1), 
                path: path 
            });
        }, function (err, data) {
            if (err) return callback(err);
    
            // add the files to the zip
            archive.addFiles(data, function (err) {
                if (err) return callback(err);
    
                // write the zip file
                fs.writeFile(dir + ".zip", archive.toBuffer(), function (err) {
                    if (err) return callback(err);
    
                    callback(null, dir + ".zip");
                });                    
            });
        });    
    }
    

    【讨论】:

    • 非常感谢! zip 已创建,但不幸的是它已损坏并显示为空。我会尝试一下,看看问题出在哪里。
    • 实际上,它似乎只是稍微损坏了;)当我尝试探索创建的 zip 时,它看起来是空的,但是当我提取它时,内容看起来很好。感谢您的快速回答!
    【解决方案2】:

    使用节点的内置 execfile 函数可以更简单地完成此操作。它产生一个进程并通过操作系统本地执行 zip 命令。一切正常。

    var execFile = require('child_process').execFile;
    
    execFile('zip', ['-r', '-j', zipName, pathToFolder], function(err, stdout) {
            console.log(err);
            logZipFile(localPath);
        });
    

    -j 标志“垃圾”文件路径,如果您正在压缩 sib 目录,并且不希望在 zip 文件中过度嵌套。

    这里是some documentation on execfile。 这是a man page for zip

    【讨论】:

    • 操作人员明确表示他们想要原生和跨平台,而不是命令行调用。
    【解决方案3】:

    使用Easy-zipnpm install easy-zip,您可以:

    var zip5 = new EasyZip();
    zip5.zipFolder('../easy-zip',function(){
        zip5.writeToFile('folderall.zip');
    });
    

    【讨论】:

    • 我不推荐使用这个因为this issue
    • 我最近一直在使用easy-zip,并没有遇到@rax 强调的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多