-
Hi, I want to use this module to dynamically generate a EPUB file. It is basically a zip that has nested directories where I want to put my runtime generated files in. I cannot seem to find an example to achieve this. Can someone tell me how to do this? Thanks! PS: Not sure if this is relative: the project I'm working on only runs in Node. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There is a wiki that provides an example of how to make a ZIP file generator in a web browser. It incrementally appends data like you ask, but from a file rather than from generated data. But the concepts are similar: here's how I would do it. // Zip: full zip archive
// ZipDeflate: zip file using compression
// ZipPassThrough: zip file uncompressed
// AsyncZipDeflate: zip compression offloaded to a separate thread
// EncodeUTF8: text to binary conversion
const { Zip, ZipDeflate, EncodeUTF8, ZipPassThrough } = require('fflate');
const chunks = [];
const zip = new Zip((err, chunk, final) => {
if (err) throw err;
// You can also write this to another stream (like a file) rather than collecting and concatenating
chunks.push(final);
if (final) {
// last chunk written
const result = Buffer.concat(chunks);
console.log('got EPUB as buffer:', result);
}
});
const addDir = name => {
const dir = new ZipPassThrough(name + '/');
zip.add(dir);
// make every directory an empty file
dir.push(new Uint8Array(0), true);
}
// returns an object where you can push binary data, e.g. an image
const addBinaryFile = name => {
const file = new ZipPassThrough(name);
zip.add(file);
return file;
}
// returns an object where you can push text data
const addTextFile = name => {
const file = new ZipDeflate(name);
zip.add(file);
// Write strings to this, get binary data out and pipe to file
const writer = new EncodeUTF8((data, final) => file.push(data, final));
return writer;
}
addDir('META-INF');
addDir('OPS');
const contentOPF = addTextFile('OPS/content.opf');
contentOPF.push('your text here', false);
contentOPF.push('more text', false);
// on the last chunk, the second argument is true
contentOPF.push('end', true);
const image = addBinaryFile('OPS/image0.jpg');
image.push(require('fs').readFileSync('image0.jpg'), true);
// important: after you've added all your data, call this:
zip.end(); |
Beta Was this translation helpful? Give feedback.
There is a wiki that provides an example of how to make a ZIP file generator in a web browser. It incrementally appends data like you ask, but from a file rather than from generated data. But the concepts are similar: here's how I would do it.