Returning multiple files as a stream

i want to return multiple files by archiving them but for some reason the resulted archive is corrupted
ts

export const readAllHandler: RouteHandler<
typeof readAllRoute,
AuthorizationBinding
> = async (c) => {
const { tags } = c.req.valid('query');
const storeId = c.get('storeId');

const matchedFiles = (
await db.query.fileTable.findMany({
where: and(
eq(fileTable.storeId, storeId),
arrayContains(fileTable.tags, tags),
),
})
).map((entry) => Bun.file(getFilePath(entry)));

if (matchedFiles.length === 0) return c.notFound();

const res = honoStream(c, async (stream) => {
const tar = archiver('tar');

tar.on('data', (chunk) => {
stream.write(chunk);
});

tar.on('end', () => {
stream.close();
});

for (let file of matchedFiles) {
if (!(await file.exists())) continue;
await file.stream().pipeTo(
new WritableStream({
write(chunk) {
tar.write(chunk);
},
}),
);
}

tar.end();
});

res.headers.append('Content-Type', 'application/x-tar');
res.headers.append('Content-Disposition', 'attachment; filename="files.tar"');
return res;
};
ts

export const readAllHandler: RouteHandler<
typeof readAllRoute,
AuthorizationBinding
> = async (c) => {
const { tags } = c.req.valid('query');
const storeId = c.get('storeId');

const matchedFiles = (
await db.query.fileTable.findMany({
where: and(
eq(fileTable.storeId, storeId),
arrayContains(fileTable.tags, tags),
),
})
).map((entry) => Bun.file(getFilePath(entry)));

if (matchedFiles.length === 0) return c.notFound();

const res = honoStream(c, async (stream) => {
const tar = archiver('tar');

tar.on('data', (chunk) => {
stream.write(chunk);
});

tar.on('end', () => {
stream.close();
});

for (let file of matchedFiles) {
if (!(await file.exists())) continue;
await file.stream().pipeTo(
new WritableStream({
write(chunk) {
tar.write(chunk);
},
}),
);
}

tar.end();
});

res.headers.append('Content-Type', 'application/x-tar');
res.headers.append('Content-Disposition', 'attachment; filename="files.tar"');
return res;
};
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server