Reading a zip file from a Cloudflare Worker

tl;dr - Example repo: https://github.com/jmorrell/cloudflare-read-zip-file-example

I needed to add some import / export functionality to a project, and ran into the problem of working with zip files on Cloudflare workers.

The standard library for working with Zip files seems to be zip.js but this is quite a large dependency. While that might not matter for a long-running Node app, on Workers your code must be downloaded and parsed on every cold start, so avoiding big dependencies where possible is usually worth it.

For creating the zip files I found littlezipper, which has worked well, however I did not find a similarly small alternative for reading zip files.

However this is exactly the kind of small, well-defined problem that LLMs are actually really good at solving. We have a well-defined widely-used file format, and a set of JavaScript APIs for doing stream manipulation, and both should be well-represented in the training data of a modern LLM.

With some prompting Claude came up with ZipReader implementation and a set of tests that should satisfy my use-case.

const arrayBuffer = await file.arrayBuffer();
const zipReader = new ZipReader(arrayBuffer);

console.log(`Processing zip file: ${file.name}`);
console.log(`Total entries: ${zipReader.getFiles().length}`);

for (const fileInfo of zipReader.getFiles()) {
  console.log(fileInfo.filename);
}

Both my implementation and littlezipper are pretty limited in that:

  • They only support the “Deflate” compression method, which seems to be the most common
  • Both require holding all of the file contents in memory, which will be a problem for larger files with Worker’s 128MB memory constraint

A better approach might be to leverage R2 (or the new node:fs support) for storage and HTTP Ranged Reads to only ever hold part of the file in memory at any given time, but that will have to wait for another day. rinsuki/async-zip-reader seems to implement this approach, but it brings in its own dependencies, and I have not tried it out.