【问题标题】:Create ZIP file in memory using any node module使用任何节点模块在内存中创建 ZIP 文件
【发布时间】:2017-03-24 06:13:45
【问题描述】:

是否有任何节点模块可以在内存中创建 zip?(我不想将 zip 文件保存在磁盘上)以便我们可以将此创建的 zip 文件发送到其他服务器(从内存)。做这个的最好方式是什么? 这是我的例子:

var file_system = require('fs');
var archiver = require('archiver');
var dirToCompress = 'directoryToZIP';

module.exports = function (req, res, next) {
var archive = archiver.create('zip', {});
archive.on('error', function (err) {
    throw err;
});

    var output = file_system.createWriteStream('/testDir/myZip.zip',{flags:'a'});//I don't want this line
    output.on('close', function () {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    archive.pipe(output);

    archive.directory(dirToCompress);

    archive.finalize();

};

【问题讨论】:

  • 我建议使用archiver 并通过管道将流进行响应,这样您就不必将任何内容写入磁盘。
  • 这里输出变量将是其他服务器的api,以便我们可以发送这个zip文件。

标签: node.js stream zip


【解决方案1】:

我正在使用Adm-Zip

// create archive
var zip = new AdmZip();

// add in-memory file
var content = "inner content of the file";
zip.addFile("test.txt", Buffer.alloc(content.length, content), "entry comment goes here");

// add file
zip.addLocalFile("/home/me/some_picture.png");

// get in-memory zip
var willSendthis = zip.toBuffer();

【讨论】:

    【解决方案2】:

    如果 GZip 可以,您可以使用the built-in zlib module,甚至不必加载外部模块。

    const gzip = zlib.createGzip();
    
    // If you have an inputStream and an outputStream:
    
    inputStream.pipe(gzip).pipe(outputStream);
    

    对于 Zip 而不是 GZip,您可以查看 archiverzip-stream

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 2017-02-28
      • 1970-01-01
      • 2023-03-21
      • 2016-09-23
      • 2015-09-28
      • 2017-07-19
      • 2014-06-30
      相关资源
      最近更新 更多