如何使用节点js将多个文件转换为压缩的zip文件 [英] how to convert multiple files to compressed zip file using node js

查看:588
本文介绍了如何使用节点js将多个文件转换为压缩的zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个文件转换为node.js上的压缩zip文件.

I want to convert multiple files to a compressed zip file on node.js.

我尝试了以下代码:

var archiver = require('archiver');
var fs = require('fs');
var StringStream = require('string-stream');

http.createServer(function(request, response) {
    var dl = archiver('data');
    dl.pipe(response);
    dl.append(new fs.createReadStream('test/fixtures/test.txt'), {
        name: 'stream.txt', date: testDate2
    });
    dl.append(new StringStream("Ooh dynamic stuff!"), {
        name : 'YoDog/dynamic.txt'
    });
    dl.finalize(function(err) {
        if (err)
            res.send(200000)
    });
}).listen(3500);

推荐答案

使用 archiver 模块:

var fs = require('fs');
var archiver = require('archiver');
var output = fs.createWriteStream('./example.zip');
var archive = archiver('zip', {
    gzip: true,
    zlib: { level: 9 } // Sets the compression level.
});

archive.on('error', function(err) {
  throw err;
});

// pipe archive data to the output file
archive.pipe(output);

// append files
archive.file('/path/to/file0.txt', {name: 'file0-or-change-this-whatever.txt'});
archive.file('/path/to/README.md', {name: 'foobar.md'});

//
archive.finalize();

它还支持tar存档,只需在第4行将"zip"替换为"tar"即可.

It also supports tar archives, just replace 'zip' by 'tar' at line 4.

我对此代码一无所知,它只是自述文件的一部分(您应该检查一下以便将其添加到存档中的其他方式).

I get no credit for this code, it's just part of the README (you should check it out for other means of adding stuff into the archive).

整洁的软件包,它可能是唯一仍在维护和正确记录的软件包.

Neat package, and it's probably the only one that's still being maintained and documented properly.

这篇关于如何使用节点js将多个文件转换为压缩的zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆