以下代码将压缩一个文件。如何压缩多个文件?
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
以下代码将压缩一个文件。如何压缩多个文件?
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
这方面最好的包(也是唯一一个仍然维护和文档齐备的)似乎是 archiver
。
var fs = require('fs');
var archiver = require('archiver');
var output = fs.createWriteStream('./example.tar.gz');
var archive = archiver('tar', {
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'});
// Wait for streams to complete
archive.finalize();
module.exports = class ZlibModule{
listOfImages = ['a.png','b.jpg'];
fs = require('fs')
zlib = require('zlib');
constructor(req,res){
this.req = req;
this.res = res;
}
compressOperation(){
this.listOfImages.forEach((value,index) => {
const readStream = this.fs.createReadStream(rootDirectory+'/modules/zlibModule/images/'+value);
const writeStream = this.fs.createWriteStream(rootDirectory+'/modules/zlibModule/'+value+'.gz');
const compress = this.zlib.createGzip()
readStream
.on('error',(error)=>{
this.res.end(`${error.path} path does't exist`)
})
.pipe(compress)
.pipe(writeStream)
.on('error',(error)=>{
console.log(error);
this.res.end(`Something went to wrong`)
})
.on('finish',()=>{
if(index+1 === this.listOfImages.length) this.res.end("Done");
})
});
}
}
以下是您可以使用的内容:
var listOfFiles = ['firstFile.txt', 'secondFile.txt', 'thirdFile.txt'];
function compressFile(filename, callback) {
var compress = zlib.createGzip(),
input = fs.createReadStream(filename),
output = fs.createWriteStream(filename + '.gz');
input.pipe(compress).pipe(output);
if (callback) {
output.on('end', callback);
}
}
#1 方法:
// Dummy, just compress the files, no control at all;
listOfFiles.forEach(compressFile);
#2 方法:
// Compress the files in waterfall and run a function in the end if it exists
function getNext(callback) {
if (listOfFiles.length) {
compressFile(listOfFiles.shift(), function () {
getNext(callback);
});
} else if (callback) {
callback();
}
}
getNext(function () {
console.log('File compression ended');
});