我想将多个文件转换为node.js上的压缩zip文件.
我尝试了以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
Ove*_*ivr 15
该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();
Run Code Online (Sandbox Code Playgroud)
它还支持tar存档,只需在第4行用'tar'替换'zip'.
我对此代码没有任何赞誉,它只是README的一部分(你应该检查一下将其他东西添加到存档中).
整洁的包装,它可能是唯一一个仍在维护和记录正确的包.
要压缩多个文件,您可以使用我用 archiver 模块编写的实用方法:-
var zipLogs = function(working_directory) {
var fs = require('fs');
var path = require('path');
var output = fs.createWriteStream(path.join(working_directory, 'logs.zip'));
var archiver = require('archiver');
var zipArchive = archiver('zip');
zipArchive.pipe(output);
zipArchive.bulk([{src: [path.join(working_directory, '*.log')], expand: true}]);
zipArchive.finalize(function(err, bytes) {
if (err)
throw err;
console.log('done:', base, bytes);
});
}
Run Code Online (Sandbox Code Playgroud)
例如,将所有日志文件压缩到特定目录中。
| 归档时间: |
|
| 查看次数: |
12761 次 |
| 最近记录: |