How to use zlib to compress multiple files? #195
-
I'm trying to replace code that I have working for a while that was using node-archiver when I try fflate with the const archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
}); So I tried to use zlib from fflate but I don't understand how to use it. Is it supposed to produce a So far this is what I have, it kinda works with gzip but I'd like to use zlib if possible and if I just replace the gzip with zlib then it says the output file is not a valid zip when I try to open it. const myFiles = [
{ name: 'package.json', path: './package.json' },
{ name: 'my-lib.js', path: './dist/my-lib.js' }.
];
let fileLeft = myFiles.length;
let filesLengths = {};
const fileToU8 = (file, cb) => {
cb(strToU8(fs.readFileSync(file.path)));
};
let processFile = (i) => {
let file = myFiles[i];
fileToU8(file, (buf) => {
zlib(buf, {
level: 6,
// The following are optional, but fflate supports metadata if you want
mtime: file.lastModified,
filename: file.name
}, (err, data) => {
if (err) { console.log('error', err); }
else {
filesLengths[file.name] = [data.length, file.size];
// If everyone else has finished processing already...
if (!--fileLeft) {
// write to file
fs.writeFileSync(`my-file.zip`, data);
}
}
});
});
};
for (let i = 0; i < myFiles.length; ++i) {
processFile(i);
} I'd really like to use fflate in my project since it's fast and it's ESM as opposed to node-archiver which is not, but I want to have the same output file size. I don't mind compressing twice if that is what I need to do but I just can't find how to do all of that and I'm confused with the docs below is an example of the file compression difference with node-archiver and fflate node-archiverfflate with
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
GZIP, Zlib, and DEFLATE are all the same compression format. Files compressed into each format should always be within 20 bytes of each other in size, all else being equal; the only differences are the headers. The reason fflate is performing worse here is that it uses its own DEFLATE implementation, while node-archiver uses the one built into Node.js. This is important for supporting web browsers, but here it's clearly a disadvantage. If you're sure you're using level 9 compression for both node-archiver and fflate, then there's not much more you can do. The difference in compression ratio of 1% is within the range of variance I'd expect between fflate's DEFLATE implementation and the Node.js one. You'll either have to live with the worse performance or continue using node-archiver. I will say that for other files you'll find fflate actually compresses much better than node-archiver; it all depends on the data. |
Beta Was this translation helpful? Give feedback.
Yes, pretty much.
zip
andzipSync
are the best ways to compress zip files withfflate
and use the same compression algorithm as node-archiver. I'm glad you've found the library useful!