Created
May 7, 2023 14:21
-
-
Save Omochice/d30508d234e4d0fd3dc9b1f70d39b629 to your computer and use it in GitHub Desktop.
This file contains 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 { dirname, join } from "https://deno.land/std@0.182.0/path/mod.ts"; | |
import { | |
BlobWriter, | |
Entry, | |
ZipReader, | |
} from "https://deno.land/x/zipjs@v2.7.6/index.js"; | |
interface Option { | |
destination: string; | |
} | |
/** | |
* unzip from ReadableStream | |
* | |
* @example | |
* ```ts | |
* const r = await fetch("https://github.com/cli/cli/archive/refs/tags/v2.28.0.zip") | |
* unzip(r.body, { destination: "~/Downloads" }) | |
* ``` | |
*/ | |
export async function unzip( | |
stream: ReadableStream, | |
option?: Option, | |
): Promise<void> { | |
const reader = new ZipReader(stream); | |
const baseDir = option?.destination ?? Deno.cwd(); | |
Promise.all((await reader.getEntries()) | |
.map(async (entry: Entry) => { | |
if (entry.directory) { | |
Deno.mkdir(join(baseDir, entry.filename), { recursive: true }); | |
return; | |
} | |
if (entry.getData == null) return; | |
const data = await entry.getData(new BlobWriter()); | |
const path = join(baseDir, entry.filename); | |
Deno.mkdirSync(dirname(path), { recursive: true }); | |
Deno.writeFile( | |
path, | |
new Uint8Array(await data.arrayBuffer()), | |
); | |
})); | |
reader.close(); | |
} | |
async function main() { | |
const r = await fetch( | |
"https://github.com/cli/cli/archive/refs/tags/v2.28.0.zip", | |
); | |
if (r.body == null) { | |
console.error(`Request returns ${r.status}. body is nully.`); | |
return; | |
} | |
unzip(r.body, { | |
destination: join(Deno.env.get("HOME") ?? "~", "Downloads"), | |
}); | |
} | |
if (import.meta.main) { | |
await main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment