Last active
April 30, 2025 19:46
-
-
Save tracker1/8a97ec86e7dfaea0c8806154ad279295 to your computer and use it in GitHub Desktop.
Create .zip file from directory with Deno in TypeScript (JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { exists } from "jsr:@std/fs"; | |
import * as zip from "jsr:@zip-js/zip-js"; | |
import { glob } from "npm:glob"; | |
import * as path from "jsr:@std/path"; | |
/** | |
* Zip the contents of a directory into a .zip file | |
*/ | |
export async function zipDir(directoryPath: string, zipFilePath: string) { | |
if (await exists(zipFilePath)) { | |
throw new Error(`The zip file (${zipFilePath}) already exists.`); | |
} | |
if (!(await exists(directoryPath, { isDirectory: true }))) { | |
throw new Error( | |
`The specified directory (${directoryPath}) does not exist.`, | |
); | |
} | |
console.log(`Creating ${zipFilePath}`); | |
zip.configure({ chunkSize: 128, useWebWorkers: true }); | |
const wf = Deno.createSync(zipFilePath); | |
const w = new zip.ZipWriter(wf, { | |
level: 9, | |
useUnicodeFileNames: true, | |
}); | |
const files = await glob(`${directoryPath}/**/*`, { | |
cwd: directoryPath, | |
maxDepth: 10, | |
nodir: true, | |
}); | |
for (let f of files) { | |
f = f.replace(/\\/g, "/"); | |
console.log(`Adding ${f}`); | |
await w.add( | |
f, | |
(await Deno.open(path.resolve(directoryPath, f), { | |
read: true, | |
write: false, | |
})) | |
.readable, | |
); | |
} | |
await w.close(); | |
console.log(`Finished ${zipFilePath}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment