einicher.net

The Code must do the talking.

ZIP whole dir with deno

28. June 2021

Compressing a whole directory as a zip archive is actually quite trivial, its just not well documented (by now):

import { zipDir } from 'https://deno.land/x/jszip/mod.ts';

const zip = await zipDir('path/to/my/folder');
zip.writeFile('path/to/destination.zip');

If you need the archive for direct output you use method generateAsync. You can choose between several output types like base64, blob, array and unit8array. If you need it for another deno operation, you will probably go with uint8array, since this is what deno uses internally.

await zip.generateAsync({
	type: 'uint8array'
});

For example, you can output the zip file with deno http respond like this:

import { serve } from "https://deno.land/std@0.95.0/http/server.ts";
import { zipDir } from 'https://deno.land/x/jszip/mod.ts';

const server = serve({ port: 8000 });

console.log('http://localhost:8000');

const zip = await zipDir('./path/to/my/folder');

for await (const request of server) {
	const zipFile = await zip.generateAsync({ type: 'uint8array' });
	request.respond({
		headers: new Headers({
			'content-type': 'application/zip',
			'content-disposition': 'attachment; filename=nameOfMyZip.zip'
		}),
		body: zipFile // can handle uint8array here
	});
}
Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *