|
1 | 1 | import { Entry as ZipEntry, open, Options as ZipOptions, ZipFile } from "yauzl"; |
2 | 2 | import { Readable } from "stream"; |
| 3 | +import { dirname, join } from "path"; |
| 4 | +import { WriteStream } from "fs"; |
| 5 | +import { createWriteStream, ensureDir } from "fs-extra"; |
3 | 6 |
|
4 | 7 | // We can't use promisify because it picks up the wrong overload. |
5 | 8 | export function openZip( |
@@ -77,3 +80,63 @@ export async function openZipBuffer( |
77 | 80 | }); |
78 | 81 | }); |
79 | 82 | } |
| 83 | + |
| 84 | +async function copyStream( |
| 85 | + readable: Readable, |
| 86 | + writeStream: WriteStream, |
| 87 | +): Promise<void> { |
| 88 | + return new Promise((resolve, reject) => { |
| 89 | + readable.on("error", (err) => { |
| 90 | + reject(err); |
| 91 | + }); |
| 92 | + readable.on("end", () => { |
| 93 | + resolve(); |
| 94 | + }); |
| 95 | + |
| 96 | + readable.pipe(writeStream); |
| 97 | + }); |
| 98 | +} |
| 99 | + |
| 100 | +export async function unzipToDirectory( |
| 101 | + archivePath: string, |
| 102 | + destinationPath: string, |
| 103 | +): Promise<void> { |
| 104 | + const zipFile = await openZip(archivePath, { |
| 105 | + autoClose: false, |
| 106 | + strictFileNames: true, |
| 107 | + lazyEntries: true, |
| 108 | + }); |
| 109 | + |
| 110 | + try { |
| 111 | + const entries = await readZipEntries(zipFile); |
| 112 | + |
| 113 | + for (const entry of entries) { |
| 114 | + const path = join(destinationPath, entry.fileName); |
| 115 | + |
| 116 | + if (/\/$/.test(entry.fileName)) { |
| 117 | + // Directory file names end with '/' |
| 118 | + |
| 119 | + await ensureDir(path); |
| 120 | + } else { |
| 121 | + // Ensure the directory exists |
| 122 | + await ensureDir(dirname(path)); |
| 123 | + |
| 124 | + const readable = await openZipReadStream(zipFile, entry); |
| 125 | + |
| 126 | + let mode: number | undefined = entry.externalFileAttributes >>> 16; |
| 127 | + if (mode <= 0) { |
| 128 | + mode = undefined; |
| 129 | + } |
| 130 | + |
| 131 | + const writeStream = createWriteStream(path, { |
| 132 | + autoClose: true, |
| 133 | + mode, |
| 134 | + }); |
| 135 | + |
| 136 | + await copyStream(readable, writeStream); |
| 137 | + } |
| 138 | + } |
| 139 | + } finally { |
| 140 | + zipFile.close(); |
| 141 | + } |
| 142 | +} |
0 commit comments