Created
June 4, 2024 17:45
-
-
Save andersonbosa/b551bd829477ab93a41770cd5f9d5c82 to your computer and use it in GitHub Desktop.
using npmjs.com/archiver package to create zip archive with given structure
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
interface FileEntry { | |
path: string | |
buffer?: Buffer | |
contents?: FileEntry[] | |
} | |
async function zipFiles (files: FileEntry[]): Promise<Buffer> { | |
const archive = archiver('zip', { zlib: { level: 9 } }) | |
const output: Buffer[] = [] | |
archive.on('data', (data: Buffer) => output.push(data)) | |
archive.on('error', (err: any) => { throw err }) | |
const addFilesToArchive = (entries: FileEntry[], rootPath = '') => { | |
for (const entry of entries) { | |
const fullPath = path.join(rootPath, entry.path) | |
if (entry.contents) { | |
addFilesToArchive(entry.contents, fullPath) | |
} else if (entry.buffer) { | |
archive.append(entry.buffer, { name: fullPath }) | |
} | |
} | |
} | |
addFilesToArchive(files) | |
await archive.finalize() | |
return Buffer.concat(output) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment