Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Created June 4, 2024 17:45
Show Gist options
  • Save andersonbosa/b551bd829477ab93a41770cd5f9d5c82 to your computer and use it in GitHub Desktop.
Save andersonbosa/b551bd829477ab93a41770cd5f9d5c82 to your computer and use it in GitHub Desktop.
using npmjs.com/archiver package to create zip archive with given structure
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